Skip to content

Commit 5767efd

Browse files
authored
Create 0024-swap-nodes-in-pairs.kt
1 parent 17220e8 commit 5767efd

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

Diff for: kotlin/0024-swap-nodes-in-pairs.kt

+30
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
/**
2+
* Example:
3+
* var li = ListNode(5)
4+
* var v = li.`val`
5+
* Definition for singly-linked list.
6+
* class ListNode(var `val`: Int) {
7+
* var next: ListNode? = null
8+
* }
9+
*/
10+
class Solution {
11+
fun swapPairs(head: ListNode?): ListNode? {
12+
var dummy = ListNode(0, head)
13+
var prev = dummy
14+
var cur = head
15+
16+
while (cur != null && cur.next != null) {
17+
val next = cur.next
18+
val nextNext = cur.next.next
19+
20+
next.next = cur
21+
cur.next = nextNext
22+
prev.next = next
23+
24+
prev = cur
25+
cur = nextNext
26+
}
27+
28+
return dummy.next
29+
}
30+
}

0 commit comments

Comments
 (0)