题目描述
编写一个程序,找到两个单链表相交的起始节点。
如下面的两个链表:
在节点 c1 开始相交。
分析
截去较长链表前面多的部分,然后往后依次比较两个等长链表的元素。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
if(!headA || !headB) return nullptr;
ListNode *countA = headA;
ListNode *countB = headB;
int lA = 0;
int lB = 0;
while(countA){
++ lA;
countA = countA -> next;
}
while(countB){
++ lB;
countB = countB -> next;
}
int i = max(lA,lB) - min(lA,lB);
if(lA > lB) for(i; i > 0; -- i) headA = headA -> next;
else for(i; i > 0; -- i) headB = headB -> next;
while(headA){
if(headA == headB) return headA;
headA = headA -> next;
headB = headB -> next;
}
return nullptr;
}
};
双指针法
循环完一个链表后,继续循环另一个,最终两个指针会在交点处相遇。
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
auto a=headA,b=headB;
while(a!=b){
if(a) a=a->next;
else a=headB;
if(b) b=b->next;
else b=headA;
}
return a;
}
};