-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathLinkedList.kt
48 lines (37 loc) · 1.22 KB
/
LinkedList.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
fun main() {
val linkedList = LinkedList(data = 2)
insertItemInLinkedListEnd(linkedList, 5)
insertItemInLinkedListEnd(linkedList, 10)
insertItemInLinkedListEnd(linkedList, 12)
insertItemInLinkedListEnd(linkedList, 13)
println("LinkedList: $linkedList")
println("Reverse: ${reverseLinkedList_02(linkedList)}" )
}
fun insertItemInLinkedListEnd(head: LinkedList, data: Int) {
if (head.next == null) {
head.next = LinkedList(data, null)
} else {
insertItemInLinkedListEnd(head.next!!, data)
}
}
fun reverseLinkedList(linkedList: LinkedList): LinkedList? {
if (linkedList.next == null) return linkedList
var next: LinkedList? = null
var prv: LinkedList? = null
var current = linkedList
while (current.next != null) {
next = current.next!!
current.next = prv
prv = current
current = next
}
return prv
}
fun reverseLinkedList_02(linkedList: LinkedList?): LinkedList? {
if (linkedList?.next == null) return linkedList
val newHead = reverseLinkedList_02(linkedList.next)
linkedList.next?.next = linkedList
linkedList.next = null
return newHead
}
data class LinkedList(var data: Int, var next: LinkedList? = null)