From 311b2f4fde6b4f980029bf2f4d71b7854d69d6d2 Mon Sep 17 00:00:00 2001 From: gemaxis Date: Tue, 19 Mar 2024 12:58:18 +0800 Subject: [PATCH] =?UTF-8?q?Update=200024.=E4=B8=A4=E4=B8=A4=E4=BA=A4?= =?UTF-8?q?=E6=8D=A2=E9=93=BE=E8=A1=A8=E4=B8=AD=E7=9A=84=E8=8A=82=E7=82=B9?= =?UTF-8?q?.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0024.两两交换链表中的节点.md | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/problems/0024.两两交换链表中的节点.md b/problems/0024.两两交换链表中的节点.md index b2a830a7..3d330f17 100644 --- a/problems/0024.两两交换链表中的节点.md +++ b/problems/0024.两两交换链表中的节点.md @@ -181,6 +181,23 @@ class Solution { } ``` +```java +// 将步骤 2,3 交换顺序,这样不用定义 temp 节点 +public ListNode swapPairs(ListNode head) { + ListNode dummy = new ListNode(0, head); + ListNode cur = dummy; + while (cur.next != null && cur.next.next != null) { + ListNode node1 = cur.next;// 第 1 个节点 + ListNode node2 = cur.next.next;// 第 2 个节点 + cur.next = node2; // 步骤 1 + node1.next = node2.next;// 步骤 3 + node2.next = node1;// 步骤 2 + cur = cur.next.next; + } + return dummy.next; +} +``` + ### Python: ```python