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.
只需要将listB首位相连,这样listA和listB就形成了一个带有环的链表。
这样题目就变成了
1 ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) 2 { 3 ListNode *tail, *join; 4 if (headA == NULL || headB == NULL) 5 return NULL; 6 7 for (tail = headB; tail->next != NULL; tail = tail->next); // reach tail 8 tail->next = headB; // create a circle 9 join = detectCycle(headA);10 tail->next = NULL; // keep list B as original11 12 return join;13 }14 15 ListNode *detectCycle(ListNode *head)16 {17 ListNode *fast = head, *slow = head;18 19 while (fast != NULL)20 {21 slow = slow->next;22 fast = fast->next;23 if (fast != NULL)24 fast = fast->next;25 if (fast != NULL && fast == slow) // catch slow26 break;27 }28 29 if (fast == NULL)30 return NULL;31 32 slow = head;33 while (slow != fast)34 {35 slow = slow->next;36 fast = fast->next;37 }38 return slow;39 }