From e98fb5a56f256371d01ed7e9456aa0fde805626f Mon Sep 17 00:00:00 2001 From: evanlai Date: Sun, 30 May 2021 14:21:41 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=20=E9=9D=A2=E8=AF=95?= =?UTF-8?q?=E9=A2=9802.07.=E9=93=BE=E8=A1=A8=E7=9B=B8=E4=BA=A4=20python3?= =?UTF-8?q?=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/面试题02.07.链表相交.md | 37 +++++++++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/problems/面试题02.07.链表相交.md b/problems/面试题02.07.链表相交.md index 13014dd1..78f34e71 100644 --- a/problems/面试题02.07.链表相交.md +++ b/problems/面试题02.07.链表相交.md @@ -151,7 +151,44 @@ public class Solution { ``` Python: +```python +# 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: + 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 + + gap = lengthA - lengthB #求长度差 + while(gap!=0): + curA = curA.next #让curA和curB在同一起点上 + gap -= 1 + + while(curA!=None): + if curA == curB: + return curA + else: + curA = curA.next + curB = curB.next + return None +``` Go: