-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
0143-reorder-list.kt
50 lines (43 loc) · 1.12 KB
/
0143-reorder-list.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
/**
* Example:
* var li = ListNode(5)
* var v = li.`val`
* Definition for singly-linked list.
* class ListNode(var `val`: Int) {
* var next: ListNode? = null
* }
*/
class Solution {
fun reorderList(head: ListNode?): Unit {
if (head == null || head.next == null)
return
var slow = head
var fast = head.next
while (fast != null && fast.next != null && slow != null) {
fast = fast.next.next
slow = slow.next
}
var reversed = reverse(slow!!.next)
slow.next = null
var curr = head
while (curr != null && reversed != null) {
val next = curr.next
val revNext = reversed.next
curr.next = reversed
reversed.next = next
curr = next
reversed = revNext
}
}
fun reverse(node: ListNode?): ListNode? {
var prev: ListNode? = null
var curr = node
while (curr != null) {
var next = curr.next
curr.next = prev
prev = curr
curr = next
}
return prev
}
}