LeetCode 160. Intersection of Two Linked Lists
1 class Solution { 2 public: 3 int length(ListNode* head){ 4 ListNode* tmp = head; 5 int len = 0; 6 while(tmp != NULL){ 7 ++ len; 8 tmp = tmp->next; 9 } 10 return len; 11 } 12 ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) { 13 int lenA = length(headA), lenB = length(headB); 14 if(lenA > lenB){ 15 int diff = lenA - lenB; 16 for(int i = 0; i < diff; ++i) 17 headA = headA->next; 18 } 19 else if(lenA < lenB){ 20 int diff = lenB - lenA; 21 for(int i = 0; i < diff; ++i) 22 headB = headB->next; 23 } 24 while(headA != headB){ 25 headA = headA->next; 26 headB = headB->next; 27 } 28 return headA; 29 } 30 };
题意是只需给出重叠的起始节点。如果一条链表比另一条更长,那么起始节点必定不在多出来的那段链上,因为head跳到之后的节点,此时两个head之后的节点数相等,再开始比较地址是否相同。
更简洁的算法:
1 class Solution { 2 public: 3 ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) { 4 if(!headA || !headB) return NULL; 5 ListNode *curA=headA, *curB=headB; 6 while(curA && curB){ 7 if(curA==curB) return curA; 8 curA=curA->next; 9 curB=curB->next; 10 /*corner cases for my code : 11 when the 2 linked-list do not meet, all the 2 pointers will be NULL at the same time. 12 the 2 pointers can be NULL at the same time, if we continue processing, the loop will 13 never end*/ 14 if(curA==curB) return curA; 15 if(curA==NULL) curA=headB; 16 if(curB==NULL) curB=headA; 17 } 18 return curA; 19 } 20 };
curA循环到A的尾巴,再跳到B头上,curB与之对应,最终必定两个节点会相遇。
具体的数学证明没看懂,留坑。
https://leetcode.com/discuss/77946/recommend-beginners-implementation-detailed-explaination