We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
1 parent 3578c89 commit 37c33a2Copy full SHA for 37c33a2
160.py
@@ -0,0 +1,21 @@
1
+# Definition for singly-linked list.
2
+# class ListNode:
3
+# def __init__(self, x):
4
+# self.val = x
5
+# self.next = None
6
+
7
+class Solution:
8
+ def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode:
9
+ ha, hb = headA, headB
10
+ while ha != hb:
11
+ ha = ha.next if ha else headB
12
+ hb = hb.next if hb else headA
13
+ return ha
14
15
+'''
16
+通常做这种题的思路是设定两个指针分别指向两个链表头部,一起向前走直到其中一个到达末端,另一个与末端距离则是两链表的 长度差。再通过长链表指针先走的方式消除长度差,最终两链表即可同时走到相交点。
17
18
+换个方式消除长度差: 拼接两链表。
19
+设长-短链表为 C,短-长链表为 D (分别代表长链表在前和短链表在前的拼接链表),则当 C 走到长短链表交接处时,D 走在长链表中,且与长链表头距离为 长度差;
20
21
0 commit comments