-
Notifications
You must be signed in to change notification settings - Fork 0
/
160.相交链表.py
54 lines (48 loc) · 1.26 KB
/
160.相交链表.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
48
49
50
51
52
53
54
#
# @lc app=leetcode.cn id=160 lang=python3
#
# [160] 相交链表
#
from typing import ListNode
# @lc code=start
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode:
pre1 = headA
pre2 = headB
stackA = []
stackB = []
lenA = 0
lenB = 0
while pre1:
stackA.append(pre1)
lenA += 1
pre1 = pre1.next
while pre2:
stackB.append(pre2)
lenB += 1
pre2 = pre2.next
node = None
for i in range(min(lenA, lenB)):
A = stackA.pop()
B = stackB.pop()
if A != B:
break
else:
node = A
return node
# @lc code=end
class Solution2:
def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode:
if( headA == None or headB == None ):
return None
pointA = headA
pointB = headB
while pointA != pointB:
pointA = pointA.next if pointA else headB
pointB = pointB.next if pointB else headA
return pointA