From 50632bc383163e690ee274867481b64070e7ca51 Mon Sep 17 00:00:00 2001 From: huhaonan <812559558@qq.com> Date: Thu, 8 Dec 2022 09:58:53 +0800 Subject: [PATCH] =?UTF-8?q?Java=E7=89=88=E6=9C=AC=E6=8C=89=E7=85=A7?= =?UTF-8?q?=E8=A7=86=E9=A2=91=E7=9A=84=E6=80=9D=E8=B7=AF=E5=AE=9E=E7=8E=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../0024.两两交换链表中的节点.md | 34 +++++++++---------- 1 file changed, 17 insertions(+), 17 deletions(-) diff --git a/problems/0024.两两交换链表中的节点.md b/problems/0024.两两交换链表中的节点.md index 50775cdd..de389448 100644 --- a/problems/0024.两两交换链表中的节点.md +++ b/problems/0024.两两交换链表中的节点.md @@ -154,24 +154,23 @@ class Solution { ``` ```java -// 虚拟头结点 class Solution { - public ListNode swapPairs(ListNode head) { - - ListNode dummyNode = new ListNode(0); - dummyNode.next = head; - ListNode prev = dummyNode; - - while (prev.next != null && prev.next.next != null) { - ListNode temp = head.next.next; // 缓存 next - prev.next = head.next; // 将 prev 的 next 改为 head 的 next - head.next.next = head; // 将 head.next(prev.next) 的next,指向 head - head.next = temp; // 将head 的 next 接上缓存的temp - prev = head; // 步进1位 - head = head.next; // 步进1位 - } - return dummyNode.next; - } + ListNode dumyhead = new ListNode(-1); + dumyhead.next = head; // 设置一个虚拟头结点 + ListNode cur1 = dumyhead; // 将虚拟头结点指向head,这样方面后面做删除操作 + ListNode temp; // 临时节点,保存两个节点后面的节点 + ListNode firstnode; // 临时节点,保存两个节点之中的第一个节点 + ListNode secondnode; // 临时节点,保存两个节点之中的第二个节点 + while (cur1.next != null && cur1.next.next != null) { + temp = cur1.next.next.next; + firstnode = cur1.next; + secondnode = cur1.next.next; + cur1.next = secondnode; // 步骤一 + secondnode.next = firstnode; // 步骤二 + firstnode.next = temp; // 步骤三 + cur1 = firstnode; // cur移动,准备下一轮交换 + } + return dumyhead.next; } ``` @@ -430,3 +429,4 @@ impl Solution { +