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.
//version 1
public class Solution {
//use detect cycle technique
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
if (headA == null || headB == null) {
return null;
}
//get the tail of headA
ListNode curt = headA;
while (curt.next != null) {
curt = curt.next;
}
curt.next = headB;
ListNode result = listCycle(headA);
curt.next = null;
return result;
}
public ListNode listCycle(ListNode headA) {
ListNode slow = headA;
ListNode fast = headA;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
if (slow == fast) {
ListNode start = headA;
while (start != slow) {
start = start.next;
slow = slow.next;
}
return slow;
}
}
return null;
}
}
If two linkedlist intersects, the meeting point in second iteration must be the intersection point.
If two linked lists have no intersection, the meeting pointer in second iteration must be the tail node of both lists, which is null
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
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
if (a == null) {
a = headB;
} else {
a = a.next;
}
if (b == null) {
b = headA;
} else {
b = b.next;
}
}
return a;
}
}