Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 83086c9

Browse files
committed
添加 0024.两两交换链表中的节点.md Scala版本
1 parent 3606a62 commit 83086c9

File tree

1 file changed

+23
-1
lines changed

1 file changed

+23
-1
lines changed

‎problems/0024.两两交换链表中的节点.md

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -311,7 +311,29 @@ func swapPairs(_ head: ListNode?) -> ListNode? {
311311
return dummyHead.next
312312
}
313313
```
314-
314+
Scala:
315+
```scala
316+
// 虚拟头节点
317+
object Solution {
318+
def swapPairs(head: ListNode): ListNode = {
319+
var dummy = new ListNode(0, head) // 虚拟头节点
320+
var pre = dummy
321+
var cur = head
322+
// 当pre的下一个和下下个都不为空,才进行两两转换
323+
while (pre.next != null && pre.next.next != null) {
324+
var tmp: ListNode = cur.next.next // 缓存下一次要进行转换的第一个节点
325+
pre.next = cur.next // 步骤一
326+
cur.next.next = cur // 步骤二
327+
cur.next = tmp // 步骤三
328+
// 下面是准备下一轮的交换
329+
pre = cur
330+
cur = tmp
331+
}
332+
// 最终返回dummy虚拟头节点的下一个,return可以省略
333+
dummy.next
334+
}
335+
}
336+
```
315337

316338
-----------------------
317339
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /