Find the common length part, then check with two pointers.
1 /** 2 * Definition for singly-linked list. 3 * struct ListNode { 4 * int val; 5 * ListNode *next; 6 * ListNode(int x) : val(x), next(NULL) {} 7 * }; 8 */ 9 class Solution { 10 public: 11 ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) { 12 if (!headA || !headB) return NULL; 13 int la = 1, lb = 1; 14 ListNode *runner = headA; 15 while (runner->next) { 16 runner = runner->next; 17 la++; 18 } 19 runner = headB; 20 while (runner->next) { 21 runner = runner->next; 22 lb++; 23 } 24 if (la > lb) { 25 while (la > lb) { 26 headA = headA->next; 27 la--; 28 } 29 } else { 30 while (lb > la) { 31 headB = headB->next; 32 lb--; 33 } 34 } 35 while (headA && headA->val != headB->val) { 36 headA = headA->next; 37 headB = headB->next; 38 } 39 return headA; 40 } 41 };
时间: 2024-10-12 10:59:34