Skip to content

Commit 6ea68a3

Browse files
committed
Intersection of Two Linked Lists
1 parent 9286af4 commit 6ea68a3

File tree

1 file changed

+72
-0
lines changed

1 file changed

+72
-0
lines changed
Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
'''
2+
Write a program to find the node at which the intersection of two singly linked lists begins.
3+
4+
5+
For example, the following two linked lists:
6+
7+
A: a1 → a2
8+
9+
c1 → c2 → c3
10+
11+
B: b1 → b2 → b3
12+
begin to intersect at node c1.
13+
14+
15+
Notes:
16+
17+
If the two linked lists have no intersection at all, return null.
18+
The linked lists must retain their original structure after the function returns.
19+
You may assume there are no cycles anywhere in the entire linked structure.
20+
Your code should preferably run in O(n) time and use only O(1) memory.
21+
'''
22+
23+
# Definition for singly-linked list.
24+
class ListNode(object):
25+
def __init__(self, x):
26+
self.val = x
27+
self.next = None
28+
29+
30+
class Solution(object):
31+
def getIntersectionNode(self, headA, headB):
32+
"""
33+
:type head1, head1: ListNode
34+
:rtype: ListNode
35+
"""
36+
nodeA, nodeB = headA, headB
37+
while nodeA != nodeB:
38+
nodeA = nodeA.next if nodeA else headB
39+
nodeB = nodeB.next if nodeB else headA
40+
return nodeA
41+
42+
def getIntersectionNode_diff(self, headA, headB):
43+
"""
44+
:type head1, head1: ListNode
45+
:rtype: ListNode
46+
"""
47+
48+
def get_length(node):
49+
length = 0
50+
while node:
51+
node = node.next
52+
length += 1
53+
return length
54+
55+
len1 = get_length(headA)
56+
len2 = get_length(headB)
57+
if len1 > len2:
58+
for __ in range(len1 - len2):
59+
headA = headA.next
60+
else:
61+
for __ in range(len2 - len1):
62+
headB = headB.next
63+
while headA:
64+
if headA == headB:
65+
return headA
66+
headA = headA.next
67+
headB = headB.next
68+
return None
69+
70+
71+
if __name__ == "__main__":
72+
None

0 commit comments

Comments
 (0)