-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0160.py
46 lines (34 loc) · 1 KB
/
0160.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
# 160. 相交链表
# 编写一个程序,找到两个单链表相交的起始节点。
# 如下面的两个链表:
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
# stack
def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode:
if not headA or not headB:
return None
stackA = []
nodeA = headA
while nodeA:
stackA.append(nodeA)
nodeA = nodeA.next
lenA = len(stackA)
stackB = []
nodeB = headB
while nodeB:
stackB.append(nodeB)
nodeB = nodeB.next
lenB = len(stackB)
lastCommonNode = None
while len(stackA) and len(stackB):
tailA = stackA.pop()
tailB = stackB.pop()
if tailA == tailB:
lastCommonNode = tailA
else:
break
return lastCommonNode