Skip to content

Commit e36bc25

Browse files
authored
Create 0707-design-linked-list.kt
1 parent 15d9b76 commit e36bc25

File tree

1 file changed

+92
-0
lines changed

1 file changed

+92
-0
lines changed

Diff for: kotlin/0707-design-linked-list.kt

+92
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,92 @@
1+
class MyLinkedList() {
2+
3+
class ListNode(var `val`: Int) {
4+
var next: ListNode? = null
5+
var prev: ListNode? = null
6+
}
7+
8+
val head = ListNode(0)
9+
val tail = ListNode(0)
10+
11+
init {
12+
head.next = tail
13+
tail.prev = head
14+
}
15+
16+
fun get(index: Int): Int {
17+
var current = head.next
18+
var i = 0
19+
while( current != null && i != index) {
20+
current = current.next
21+
i++
22+
}
23+
return if(current != null && current != tail) current.`val` else -1
24+
}
25+
26+
fun addAtHead(`val`: Int) {
27+
val prev = head
28+
val next = head.next
29+
val new = ListNode(`val`)
30+
31+
head.next = new
32+
new.prev = head
33+
new.next = next
34+
next?.prev = new
35+
}
36+
37+
fun addAtTail(`val`: Int) {
38+
val next = tail
39+
val prev = tail.prev
40+
val new = ListNode(`val`)
41+
42+
tail.prev = new
43+
new.prev = prev
44+
new.next = tail
45+
prev?.next = new
46+
}
47+
48+
fun addAtIndex(index: Int, `val`: Int) {
49+
var current = head.next
50+
var i = 0
51+
while( current != null && i != index) {
52+
current = current.next
53+
i++
54+
}
55+
if(current != null) {
56+
val prev = current.prev
57+
val new = ListNode(`val`)
58+
59+
prev?.next = new
60+
new.prev = prev
61+
new.next = current
62+
current.prev = new
63+
}
64+
}
65+
66+
fun deleteAtIndex(index: Int) {
67+
var current = head.next
68+
var i = 0
69+
while( current != null && i != index) {
70+
current = current.next
71+
i++
72+
}
73+
if(current != null && current != tail) {
74+
val prev = current.prev
75+
val next = current.next
76+
77+
prev?.next = next
78+
next?.prev = prev
79+
}
80+
}
81+
82+
}
83+
84+
/**
85+
* Your MyLinkedList object will be instantiated and called as such:
86+
* var obj = MyLinkedList()
87+
* var param_1 = obj.get(index)
88+
* obj.addAtHead(`val`)
89+
* obj.addAtTail(`val`)
90+
* obj.addAtIndex(index,`val`)
91+
* obj.deleteAtIndex(index)
92+
*/

0 commit comments

Comments
 (0)