160 Intersection of Two Linked List
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.
Method1 : Find the length of two linked list and then move one list to same length
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
if (headA == null || headB == null) {
return null;
}
int lenA = len(headA);
int lenB = len(headB);
ListNode curtA = headA;
ListNode curtB = headB;
if (lenA != lenB) {
if (lenA > lenB) {
for (int i = 0; i < lenA - lenB; i++) {
curtA = curtA.next;
}
} else if (lenB > lenA){
for (int i = 0; i < lenB - lenA; i++) {
curtB = curtB.next;
}
}
}
while (curtA != null && curtB != null) {
if (curtA.val!=curtB.val) {
curtA = curtA.next;
curtB = curtB.next;
}else{
return curtA;
}
}
return null;
}
public int len(ListNode head) {
int length = 0;
while (head != null) {
head = head.next;
length++;
}
return length;
}
}
另一种方法很巧妙时间复杂度为O(M+n)
/**
*
A: a1 → a2
↘
c1 → c2 → c3
↗
B: b1 → b2 → b3
begin to intersect at node c1.
A : a1 → a2 -> c1 → c2 → c3 -> b1 → b2 → b3 -> c1 → c2 → c3
B : b1 → b2 → b3 -> c1 → c2 → c3 -> a1 → a2 -> c1 → c2 → c3
time : O(m + n);
space : O(1);
* @param headA
* @param headB
* @return
*/
public ListNode getIntersectionNode2(ListNode headA, ListNode headB) {
if (headA == null || headB == null) return null;
ListNode a = headA;
ListNode b = headB;
while (a != b) {
a = a == null ? headB : a.next;
b = b == null ? headA : b.next;
}
return a;
}
}