-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathReversal.kt
41 lines (36 loc) · 1003 Bytes
/
Reversal.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
package com.daily.algothrim.linked.algo
import com.daily.algothrim.linked.LinkedNode
/**
* 单链表反转
*/
class Reversal {
companion object {
@JvmStatic
fun main(args: Array<String>) {
Reversal().reversal(LinkedNode("a").apply {
next = LinkedNode("b").apply {
next = LinkedNode("c").apply {
next = LinkedNode("d").apply {
next = LinkedNode("a")
}
}
}
})?.printAll()
}
}
/**
* O(n)
*/
fun reversal(singleLinked: LinkedNode<String>?): LinkedNode<String>? {
var result: LinkedNode<String>? = null
var current = singleLinked
var next: LinkedNode<String>?
while (current != null) {
next = current.next
current.next = result
result = current
current = next
}
return result
}
}