Write a program to find the node at which the intersection of two singly linked lists begins.
For example, the following two linked lists:
A: a1 → a2
↘
c1 → c2 → c3
↗
B: b1 → b2 → b3
begin to intersect at node c1.
Notes:
- If the two linked lists have no intersection at all, return
null
. - The linked lists must retain their original structure after the function returns.
- You may assume there are no cycles anywhere in the entire linked structure.
- Your code should preferably run in O(n) time and use only O(1) memory.
思路:first指针指向headA,second指针指向headB,同时指向各自的后序。first走到结尾的时候,指向headB,继续走,second走到结尾的的时候,指向headA,继续走。如果有相交的结点,则会相遇。
疑问:为什么两个指针一定会在结点处相交?
解答:因为两个指针走过的总路程是相等的,都是链表A的长度加上链表B的长度,所以当指针first走到B的末尾的时候,second一定走到了A的末尾。所以如果链表A和B有结点,那么最后一段相交的结点一定是first和second一起同时走完的。只要检测到first和second走上同一个Node,那么这个Node就是结点。
/**
* 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 0;
ListNode* first = headA;
ListNode* second = headB;
while(first->next||second->next)
{
if(first == second)
return first;
if(!first->next)
first = headB;
else
first = first->next;
if(!second->next)
second = headA;
else
second = second->next;
}
if(first == second)
return first;
else
return 0;
}
};