题目:
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.
思路:设定p1、p2两个指针,分别从两个链表头端往尾端依次走。当一个指针走到了尾节点,则令其从另一个链表头端再次出发,另一个指针也是如此。在第二次途中必定相遇。A链表头节点到交点的距离为D1,B链表头节点到交点距离为D2,交点到尾端的距离为D3。因为两个指针的总距离皆为D1+D2+D3。(如果第一次就相遇的话,D1 == D2)
代码:
/**
* 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) {
ListNode* ptr1 = headA;
ListNode* ptr2 = headB;
if(ptr1 == NULL || ptr2 == NULL) return NULL;
while(ptr1 !=ptr2){
ptr1 = ptr1->next;
ptr2 = ptr2->next;
if(ptr1 == ptr2) break;
if(ptr1 == NULL) ptr1 = headB;
if(ptr2 == NULL) ptr2 = headA;
}
return ptr1;
}
};