From d7235d9f51b532dda387bf6e00be225f931ed275 Mon Sep 17 00:00:00 2001 From: NevS <1173325467@qq.com> Date: Thu, 27 May 2021 21:39:32 +0800 Subject: [PATCH 1/2] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=2002.07.=E9=93=BE?= =?UTF-8?q?=E8=A1=A8=E7=9B=B8=E4=BA=A4=20go=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 | 36 +++++++++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/problems/面试题02.07.链表相交.md b/problems/面试题02.07.链表相交.md index 9e97264c..13014dd1 100644 --- a/problems/面试题02.07.链表相交.md +++ b/problems/面试题02.07.链表相交.md @@ -155,6 +155,42 @@ Python: Go: +```go +func getIntersectionNode(headA, headB *ListNode) *ListNode { + curA := headA + curB := headB + lenA, lenB := 0, 0 + // 求A,B的长度 + for curA != nil { + curA = curA.Next + lenA++ + } + for curB != nil { + curB = curB.Next + lenB++ + } + var step int + var fast, slow *ListNode + // 请求长度差,并且让更长的链表先走相差的长度 + if lenA > lenB { + step = lenA - lenB + fast, slow = headA, headB + } else { + step = lenB - lenA + fast, slow = headB, headA + } + for i:=0; i < step; i++ { + fast = fast.Next + } + // 遍历两个链表遇到相同则跳出遍历 + for fast != slow { + fast = fast.Next + slow = slow.Next + } + return fast +} +``` + javaScript: ```js From c722642392ab8853f91ffac654149531b8117973 Mon Sep 17 00:00:00 2001 From: NevS <1173325467@qq.com> Date: Fri, 28 May 2021 00:33:17 +0800 Subject: [PATCH 2/2] =?UTF-8?q?=E6=9B=B4=E6=96=B0=200142.=E7=8E=AF?= =?UTF-8?q?=E5=BD=A2=E9=93=BE=E8=A1=A8II=20go=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 1、原先的Go版本代码显示错乱,一部分代码未显示 2、去掉多余判断,让代码更简洁 --- problems/0142.环形链表II.md | 28 +++++++++++----------------- 1 file changed, 11 insertions(+), 17 deletions(-) diff --git a/problems/0142.环形链表II.md b/problems/0142.环形链表II.md index 15c2d1f9..9deb1e0c 100644 --- a/problems/0142.环形链表II.md +++ b/problems/0142.环形链表II.md @@ -234,25 +234,19 @@ class Solution: ``` Go: -```func detectCycle(head *ListNode) *ListNode { - if head ==nil{ - return head - } - slow:=head - fast:=head.Next - - for fast!=nil&&fast.Next!=nil{ - if fast==slow{ - slow=head - fast=fast.Next - for fast!=slow { - fast=fast.Next - slow=slow.Next +```go +func detectCycle(head *ListNode) *ListNode { + slow, fast := head, head + for fast != nil && fast.Next != nil { + slow = slow.Next + fast = fast.Next.Next + if slow == fast { + for slow != head { + slow = slow.Next + head = head.Next } - return slow + return head } - fast=fast.Next.Next - slow=slow.Next } return nil }