Intersection of Two Linked Lists
Write a program to find the node at which the intersection of two singly linked lists begins.node
For example, the following two linked lists:this
A: a1 → a2指针
↘ c1 → c2 → c3 ↗
B: b1 → b2 → b3code
begin to intersect at node c1.ci
Notes:get
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.
Credits:
Special thanks to @stellari for adding this problem and creating all test cases.it
SOLUTION 1:io
获得2个链条的长度。function
将长的链条向前移动差值(len1 - len2)test
两个指针一块儿前进,遇到相同的便是交点,若是没找到,返回null.
空间复杂度O(1), 时间复杂度O(m+n)
public ListNode getIntersectionNode1(ListNode headA, ListNode headB) { if (headA == null || headB == null) { return null; } int lenA = getLen(headA); int lenB = getLen(headB); if (lenA > lenB) { while (lenA > lenB) { headA = headA.next; lenA--; } } else { while (lenA < lenB) { headB = headB.next; lenB--; } } while (headA != null) { if (headA == headB) { return headA; } headA = headA.next; headB = headB.next; } return null; } public int getLen(ListNode node) { int len = 0; while (node != null) { len++; node = node.next; } return len; }
SOLUTION 2:
Two pointer solution (O(n+m) running time, O(1) memory):
Maintain two pointers pA and pB initialized at the head of A and B, respectively. Then let them both traverse through the lists, one node at a time.
When pA reaches the end of a list, then redirect it to the head of B (yes, B, that's right.); similarly when pB reaches the end of a list, redirect it the head of A. The first iteration counteract the difference of len thus the meeting points of second iteration would be the intersection point. Return null if two lists are parallel.
public ListNode getIntersectionNode(ListNode headA, ListNode headB) { if (headA == null || headB == null) { return null; } ListNode pA = headA; ListNode pB = headB; ListNode tailA = null; ListNode tailB = null; while (true) { if (pA == null) { pA = headB; } if (pB == null) { pB = headA; } if (pA.next == null) { tailA = pA; } if (pB.next == null) { tailB = pB; } //The two links have different tails. So just return null; if (tailA != null && tailB != null && tailA != tailB) { return null; } if (pA == pB) { return pA; } pA = pA.next; pB = pB.next; } }