-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
0707-design-linked-list.kt
84 lines (70 loc) · 1.74 KB
/
0707-design-linked-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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
class MyLinkedList() {
val head = LN(0)
val tail = LN(0)
init {
head.next = tail
tail.prev = head
}
fun get(index: Int): Int {
var current = head.next
var i = 0
while (current != null && i != index) {
current = current.next
i++
}
return if (current != null && current != tail) current.`val` else -1
}
fun addAtHead (`val`: Int) {
val prev = head
val next = head.next
val new = LN(`val`)
head.next = new
new.prev = head
new.next = next
next?.prev = new
}
fun addAtTail(`val`: Int) {
val next = tail
val prev = tail.prev
val new = LN(`val`)
tail.prev = new
new.prev = prev
new.next = tail
prev?.next = new
}
fun addAtIndex(index: Int, `val`: Int) {
var current = head.next
var i = 0
while (current != null && i != index) {
current = current.next
i++
}
if (current != null) {
val prev = current.prev
val new = LN(`val`)
prev?.next = new
new.prev = prev
new.next = current
current.prev = new
}
}
fun deleteAtIndex(index: Int) {
var current = head.next
var i = 0
while (current != null && i != index) {
current = current.next
i++
}
if (current != null && current != tail) {
val prev = current.prev
val next = current.next
prev?.next = next
next?.prev = prev
}
}
}
class LN (
var `val`: Int,
var next: LN? = null,
var prev: LN? = null
)