-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathReverseLinkedList.kt
60 lines (50 loc) · 1.35 KB
/
ReverseLinkedList.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
51
52
53
54
55
56
57
58
59
60
package algorithmdesignmanualbook.datastructures
import _utils.UseCommentAsDocumentation
data class LinkedListNode(val value: Int) {
var next: LinkedListNode? = null
private set
fun add(value: Int) {
var current: LinkedListNode? = this
while (current?.next != null) {
current = current.next
}
current!!.next = LinkedListNode(value)
}
fun print() {
val sb = StringBuilder()
var current: LinkedListNode? = this
while (current != null) {
sb.append("${current.value}").append(" -> ")
current = current.next
}
println(sb.removeSuffix(" -> ").toString())
}
/**
* [link here](https://leetcode.com/problems/reverse-linked-list)
*/
@UseCommentAsDocumentation
fun reverse(): LinkedListNode? {
var prev: LinkedListNode? = null
var current: LinkedListNode? = this
if (current?.next == null) {
return this
}
while (current != null) {
val temp = current.next
current.next = prev
prev = current
current = temp
}
return prev
}
}
fun main() {
val list = LinkedListNode(1)
list.reverse()?.print()
list.add(2)
list.add(3)
list.add(4)
list.add(5)
list.print()
list.reverse()?.print()
}