-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinterview0207.py
74 lines (52 loc) · 1.78 KB
/
interview0207.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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
# leetcode 面试题 02.07 链表相交
# 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:
# 排除一些异常情况
if not headA or not headB:
return None
numA, numB = 0, 0
pointerA, pointerB = headA, headB
# list1 = [pointerA]
# while pointerA is not None:
# list1.append(pointerA.next)
# pointerA = pointerA.next
# while pointerB is not None:
# if pointerB in list1:
# return pointerB
# else:
# pointerB = pointerB.next
# return None
# 这段主要做的是 计算出来两个链分别的长度
while pointerA is not None:
pointerA = pointerA.next
numA += 1
while pointerB is not None:
pointerB = pointerB.next
numB += 1
# 判断出来他们的距离差 然后给他们对齐
dis = numA - numB
pointerA, pointerB = headA, headB
if dis < 0:
for _ in range(-dis):
pointerB = pointerB.next
else:
for _ in range(dis):
pointerA = pointerA.next
'''
while pointerA != None:
if pointerB == pointerA:
return pointerB
pointerB = pointerB.next
pointerA = pointerA.next
return None
'''
# 然后每一个都往前前进一个格子,如果有交叉,必定会重合到一起去
while pointerA != pointerB:
pointerB = pointerB.next
pointerA = pointerA.next
return pointerA