-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path160_intersection_of_two_linked_lists.py
More file actions
71 lines (56 loc) · 1.53 KB
/
160_intersection_of_two_linked_lists.py
File metadata and controls
71 lines (56 loc) · 1.53 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
def toLinkedList(list):
head = None
prev = None
current = None
for element in list:
current = ListNode(element)
try:
prev.next = current
prev = current
except:
prev = ListNode(element)
head = prev
return(head)
class Solution(object):
def getIntersectionNode(self, headA, headB):
"""
:type head1, head1: ListNode
:rtype: ListNode
"""
def length(node):
'''
Gets the length of a linked list
'''
L = 0
while node is not None:
L += 1
node = node.next
return(L)
LA = length(headA)
LB = length(headB)
currentA = headA
currentB = headB
if LB > LA:
currentA, currentB = currentB, currentA
diff = abs(LA-LB)
while diff > 0:
currentA = currentA.next
diff -= 1
while currentA is not None:
if currentA == currentB:
return(currentA)
else:
currentA = currentA.next
currentB = currentB.next
return(None)
if __name__ == '__main__':
test1 = toLinkedList([5,0,1])
test2 = toLinkedList([4,1,8,4,5])
test1.next.next.next = test2.next.next
sol = Solution()
result = sol.getIntersectionNode(test1,test2)