From 83086c903d77496e6fa34e7e4b0069e27ad1210c Mon Sep 17 00:00:00 2001 From: ZongqinWang <1722249371@qq.com> Date: Thu, 12 May 2022 10:13:00 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=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=20Scala=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../0024.两两交换链表中的节点.md | 24 ++++++++++++++++++- 1 file changed, 23 insertions(+), 1 deletion(-) diff --git a/problems/0024.两两交换链表中的节点.md b/problems/0024.两两交换链表中的节点.md index ce75e0d7..2289c229 100644 --- a/problems/0024.两两交换链表中的节点.md +++ b/problems/0024.两两交换链表中的节点.md @@ -311,7 +311,29 @@ func swapPairs(_ head: ListNode?) -> ListNode? { return dummyHead.next } ``` - +Scala: +```scala +// 虚拟头节点 +object Solution { + def swapPairs(head: ListNode): ListNode = { + var dummy = new ListNode(0, head) // 虚拟头节点 + var pre = dummy + var cur = head + // 当pre的下一个和下下个都不为空,才进行两两转换 + while (pre.next != null && pre.next.next != null) { + var tmp: ListNode = cur.next.next // 缓存下一次要进行转换的第一个节点 + pre.next = cur.next // 步骤一 + cur.next.next = cur // 步骤二 + cur.next = tmp // 步骤三 + // 下面是准备下一轮的交换 + pre = cur + cur = tmp + } + // 最终返回dummy虚拟头节点的下一个,return可以省略 + dummy.next + } +} +``` -----------------------