输入两个链表,找出它们的第一个公共结点

xiaoxiao2021-02-28  101

/* struct ListNode { int val; struct ListNode *next; ListNode(int x) : val(x), next(NULL) { } };*/ class Solution { public: ListNode* FindFirstCommonNode( ListNode* pHead1, ListNode* pHead2) { ListNode * p = pHead1; int num1 = 0; int num2 = 0; while (p) { num1++; p = p->next; } ListNode *p2 = pHead2; while(p2) { num2++; p2 = p2->next; } if (num2>num1) { int x = num2-num1; for ( int i = 0 ; i!=x ; i++) { pHead2=pHead2->next; } while (pHead2) { if (pHead2->val == pHead1->val) return pHead2; pHead2 = pHead2->next; pHead1 = pHead1->next; } }else{ int x = num1 - num2; for (int i = 0; i!= x;i++) { pHead1 = pHead1->next; } while (pHead1) { if (pHead1->val == pHead2->val) return pHead1; pHead1 = pHead1->next; pHead2 = pHead2->next; } } return NULL; } };
转载请注明原文地址: https://www.6miu.com/read-80450.html

最新回复(0)