-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathIntersectionLL.py
47 lines (33 loc) · 949 Bytes
/
IntersectionLL.py
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
from LinkedList import LinkedList, Node
def intersection(llA, llB):
if llA.tail is not llB.tail:
return False
lenA = len(llA)
lenB = len(llB)
shorter = llA if lenA < lenB else llB
longer = llB if lenA < lenB else llA
diff = len(longer) - len(shorter)
longerNode = longer.head
shorterNode = shorter.head
for i in range(diff):
longerNode = longerNode.next
while shorterNode is not longerNode:
shorterNode = shorterNode.next
longerNode = longerNode.next
return longerNode
# Helper addition method
def addSameNode(llA, llB, value):
tempNode = Node(value)
llA.tail.next = tempNode
llA.tail = tempNode
llB.tail.next = tempNode
llB.tail = tempNode
llA = LinkedList()
llA.generate(3,0, 10)
llB = LinkedList()
llB.generate(4,0, 10)
addSameNode(llA, llB, 11)
addSameNode(llA, llB, 14)
print(llA)
print(llB)
print(intersection(llA, llB))