From a24ee9c15a078d2bc1dc828322de872ce5df6879 Mon Sep 17 00:00:00 2001 From: NevS <1173325467@qq.com> Date: Wed, 26 May 2021 23:11:53 +0800 Subject: [PATCH 1/2] =?UTF-8?q?=E6=9B=B4=E6=96=B0=200019.=E5=88=A0?= =?UTF-8?q?=E9=99=A4=E9=93=BE=E8=A1=A8=E7=9A=84=E5=80=92=E6=95=B0=E7=AC=AC?= =?UTF-8?q?N=E4=B8=AA=E8=8A=82=E7=82=B9=20go=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 1、将原先代码中每次都需要获取慢指针前一个元素的方式修改成直接用慢指针进行元素的删除(代码便于理解) 2、调整代码格式 --- ...0019.删除链表的倒数第N个节点.md | 32 +++++++++++-------- 1 file changed, 18 insertions(+), 14 deletions(-) diff --git a/problems/0019.删除链表的倒数第N个节点.md b/problems/0019.删除链表的倒数第N个节点.md index 65651768..7d2fe97e 100644 --- a/problems/0019.删除链表的倒数第N个节点.md +++ b/problems/0019.删除链表的倒数第N个节点.md @@ -114,24 +114,28 @@ class Solution { ``` Go: ```Go +/** + * Definition for singly-linked list. + * type ListNode struct { + * Val int + * Next *ListNode + * } + */ func removeNthFromEnd(head *ListNode, n int) *ListNode { - result:=&ListNode{} - result.Next=head - var pre *ListNode - cur:=result - - i:=1 - for head!=nil{ - if i>=n{ - pre=cur - cur=cur.Next + dummyHead := &ListNode{} + dummyHead.Next = head + cur := head + prev := dummyHead + i := 1 + for cur != nil { + cur = cur.Next + if i > n { + prev = prev.Next } - head=head.Next i++ } - pre.Next=pre.Next.Next - return result.Next - + prev.Next = prev.Next.Next + return dummyHead.Next } ``` From b02a1c44f25823e0a09985c277f7cb41a543b2b7 Mon Sep 17 00:00:00 2001 From: NevS <1173325467@qq.com> Date: Thu, 27 May 2021 00:13:54 +0800 Subject: [PATCH 2/2] =?UTF-8?q?=E5=A2=9E=E5=8A=A0=200024.=E4=B8=A4?= =?UTF-8?q?=E4=B8=A4=E4=BA=A4=E6=8D=A2=E9=93=BE=E8=A1=A8=E4=B8=AD=E7=9A=84?= =?UTF-8?q?=E8=8A=82=E7=82=B9=E7=9A=84=E9=80=92=E5=BD=92=E8=A7=A3=E6=B3=95?= =?UTF-8?q?=20go=20=E7=89=88?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0024.两两交换链表中的节点.md | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/problems/0024.两两交换链表中的节点.md b/problems/0024.两两交换链表中的节点.md index 8d6a394d..643f6055 100644 --- a/problems/0024.两两交换链表中的节点.md +++ b/problems/0024.两两交换链表中的节点.md @@ -153,6 +153,19 @@ func swapPairs(head *ListNode) *ListNode { } ``` +```go +// 递归版本 +func swapPairs(head *ListNode) *ListNode { + if head == nil || head.Next == nil { + return head + } + next := head.Next + head.Next = swapPairs(next.Next) + next.Next = head + return next +} +``` + Javascript: ```javascript var swapPairs = function (head) {