160. Intersection of Two Linked Lists
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. Credits: Special thanks to @stellari for adding this problem and creating all test cases.
第一想法是用HashSet<ListNode>, A list先遍历,存HashSet,然后B list遍历,发现ListNode存在就返回。但是这个方法不满足O(1)memory的要求。
再想了一会儿,略微受了点提醒,发现可以利用这个O(n) time做文章。这个条件方便我们scan list几次都可以。于是我想到了:
先scan A list, 记录A list长度lenA, 再scan B list, 记录B list长度lenB. 看A list最后一个元素与 B list最后一个元素是否相同就可以知道是否intersect.
各自cursor回到各自list的开头,长的那个list的cursor先走|lenA - lenB|步,然后一起走,相遇的那一点就是所求
public ListNode getIntersectionNode(ListNode headA, ListNode headB) { int lenA = length(headA), lenB = length(headB); // move headA and headB to the same start point while (lenA > lenB) { headA = headA.next; lenA--; } while (lenA < lenB) { headB = headB.next; lenB--; } // find the intersection until end while (headA != headB) { headA = headA.next; headB = headB.next; } return headA; } private int length(ListNode node) { int length = 0; while (node != null) { length++; node = node.next; } return length; }
ote最高的做法:no need to calculate the difference in length. two pointers starts from both head. When one reach the end just set it at the head of another list. When two pointers join, that's the intersection
public ListNode getIntersectionNode(ListNode headA, ListNode headB) { //boundary check if(headA == null || headB == null) return null; ListNode a = headA; ListNode b = headB; //if a & b have different len, then we will stop the loop after second iteration while( a != b){ //for the end of first iteration, we just reset the pointer to the head of another linkedlist a = a == null? headB : a.next; b = b == null? headA : b.next; } return a; }
如果有环, If one list has cycle and the other does not. Then for sure the two do not merge.
3. If both lists have cycle, it is actually possible to find out the so-called 'last node' which is the node that is just prior to the entrance of the cycle.
for example, for list n0->n1->n2->n3->n1(entrance of cycle), the entrance of cycle can be found out (which can be done in O(n). I do not specify how, since this is the basic operation on linked list. Refer to the book 'cracking the coding interview'). Once the entrance is found, the 'last node' is gonna be the node with node.next == entrance. It CAN BE FOUND. Once the last nodes for both lists were found, simply check if they are the same node. If same, then the two lists do merge.