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

转载于:https://www.cnblogs.com/co0oder/p/5263444.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值