mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-11 21:10:58 +08:00
更新 面试题02.07 链表相交python代码
用更简单的逻辑完成这道题。
This commit is contained in:
@ -160,34 +160,21 @@ Python:
|
|||||||
|
|
||||||
class Solution:
|
class Solution:
|
||||||
def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode:
|
def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode:
|
||||||
lengthA,lengthB = 0,0
|
"""
|
||||||
curA,curB = headA,headB
|
根据快慢法则,走的快的一定会追上走得慢的。
|
||||||
while(curA!=None): #求链表A的长度
|
在这道题里,有的链表短,他走完了就去走另一条链表,我们可以理解为走的快的指针。
|
||||||
curA = curA.next
|
|
||||||
lengthA +=1
|
|
||||||
|
|
||||||
while(curB!=None): #求链表B的长度
|
|
||||||
curB = curB.next
|
|
||||||
lengthB +=1
|
|
||||||
|
|
||||||
curA, curB = headA, headB
|
|
||||||
|
|
||||||
if lengthB>lengthA: #让curA为最长链表的头,lenA为其长度
|
那么,只要其中一个链表走完了,就去走另一条链表的路。如果有交点,他们最终一定会在同一个
|
||||||
lengthA, lengthB = lengthB, lengthA
|
位置相遇
|
||||||
curA, curB = curB, curA
|
"""
|
||||||
|
cur_a, cur_b = headA, headB # 用两个指针代替a和b
|
||||||
|
|
||||||
gap = lengthA - lengthB #求长度差
|
|
||||||
while(gap!=0):
|
|
||||||
curA = curA.next #让curA和curB在同一起点上
|
|
||||||
gap -= 1
|
|
||||||
|
|
||||||
while(curA!=None):
|
while cur_a != cur_b:
|
||||||
if curA == curB:
|
cur_a = cur_a.next if cur_a else headB # 如果a走完了,那么就切换到b走
|
||||||
return curA
|
cur_b = cur_b.next if cur_b else headA # 同理,b走完了就切换到a
|
||||||
else:
|
|
||||||
curA = curA.next
|
return cur_a
|
||||||
curB = curB.next
|
|
||||||
return None
|
|
||||||
```
|
```
|
||||||
|
|
||||||
Go:
|
Go:
|
||||||
|
Reference in New Issue
Block a user