forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
0707-design-linked-list.kt
92 lines (78 loc) · 2.02 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
85
86
87
88
89
90
91
92
class MyLinkedList() {
class ListNode(var `val`: Int) {
var next: ListNode? = null
var prev: ListNode? = null
}
val head = ListNode(0)
val tail = ListNode(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 = ListNode(`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 = ListNode(`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 = ListNode(`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
}
}
}
/**
* Your MyLinkedList object will be instantiated and called as such:
* var obj = MyLinkedList()
* var param_1 = obj.get(index)
* obj.addAtHead(`val`)
* obj.addAtTail(`val`)
* obj.addAtIndex(index,`val`)
* obj.deleteAtIndex(index)
*/