From 8b94306cc6030eb79f2a8376b01f6398d888f7ed Mon Sep 17 00:00:00 2001 From: Eyjan_Huang <81480748+Eyjan-Huang@users.noreply.github.com> Date: Fri, 20 Aug 2021 03:23:30 +0800 Subject: [PATCH] =?UTF-8?q?=E6=9B=B4=E6=96=B0=200024.=E4=B8=A4=E4=B8=A4?= =?UTF-8?q?=E4=BA=A4=E6=8D=A2=E9=93=BE=E8=A1=A8=E4=B8=AD=E7=9A=84=E8=8A=82?= =?UTF-8?q?=E7=82=B9.md=20python=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 使用变量名使交换的过程更加清晰,而不是使用之前的next.next这样可读性较差 从后往前换 pre = dummy,cur = 2, post=3 dummpy -> 1 -> 2 -> None 先把cur.next = post.next,此时链表为 1 -> None 再 post.next = cur 此时链表为 2 -> 1 -> None, dummpy -> 1 -> None 最后 pre.next = post, 此时为 dummpy -> 2 -> 1 -> None --- .../0024.两两交换链表中的节点.md | 32 ++++++++++++------- 1 file changed, 20 insertions(+), 12 deletions(-) diff --git a/problems/0024.两两交换链表中的节点.md b/problems/0024.两两交换链表中的节点.md index 91e566dd..672b9a8f 100644 --- a/problems/0024.两两交换链表中的节点.md +++ b/problems/0024.两两交换链表中的节点.md @@ -160,21 +160,29 @@ class Solution { Python: ```python +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, val=0, next=None): +# self.val = val +# self.next = next + class Solution: def swapPairs(self, head: ListNode) -> ListNode: - dummy = ListNode(0) #设置一个虚拟头结点 - dummy.next = head - cur = dummy - while cur.next and cur.next.next: - tmp = cur.next #记录临时节点 - tmp1 = cur.next.next.next #记录临时节点 + res = ListNode(next=head) + pre = res + + # 必须有pre的下一个和下下个才能交换,否则说明已经交换结束了 + while pre.next and pre.next.next: + cur = pre.next + post = pre.next.next - cur.next = cur.next.next #步骤一 - cur.next.next = tmp #步骤二 - cur.next.next.next = tmp1 #步骤三 - - cur = cur.next.next #cur移动两位,准备下一轮交换 - return dummy.next + # pre,cur,post对应最左,中间的,最右边的节点 + cur.next = post.next + post.next = cur + pre.next = post + + pre = pre.next.next + return res.next ``` Go: