Leetcode[160] Intersection of Two Linked Lists
14 Nov 2015###Task1 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.
###Python
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def getIntersectionNode(self, headA, headB):
"""
:type head1, head1: ListNode
:rtype: ListNode
"""
if not headA or not headB:
return None
len1 = 0
len2 = 0
itr = headA
while itr:
itr = itr.next
len1 += 1
itr = headB
while itr:
itr = itr.next
len2 += 1
if len1 > len2:
diff = len1 - len2
while diff > 0:
headA = headA.next
diff -= 1
else:
diff = len2 - len1
while diff > 0:
headB = headB.next
diff -= 1
while headA and headB:
if headA == headB:
return headA
headA = headA.next
headB = headB.next
return None
###Java ####O(n) space
/**
* 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;
}
HashMap<ListNode, Integer> map = new HashMap<ListNode, Integer>();
int pos = 0;
while (headA != null) {
map.put(headA, pos);
headA = headA.next;
pos++;
}
while (headB != null) {
if (map.containsKey(headB)) {
return headB;
}
headB = headB.next;
}
return null;
}
}
####O(1) space
/**
* 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;
}
ListNode iterA = headA;
ListNode iterB = headB;
int lengthA = 0;
int lengthB = 0;
while (iterA != null) {
lengthA++;
iterA = iterA.next;
}
while (iterB != null) {
lengthB++;
iterB = iterB.next;
}
iterA = headA;
iterB = headB;
if (lengthA > lengthB) {
int diff = lengthA - lengthB;
for (int i = 0; i < diff; i++) {
iterA = iterA.next;
}
} else if (lengthB > lengthA) {
int diff = lengthB - lengthA;
for (int i = 0; i < diff; i++) {
iterB = iterB.next;
}
}
while (iterA != null) {
if (iterA == iterB) {
return iterA;
}
iterA = iterA.next;
iterB = iterB.next;
}
return null;
}
}
###Points
- O(n)
- No need to take special care of length1 == length2 case.