1
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 )
2
+ val head = LN (0 )
3
+ val tail = LN (0 )
10
4
11
5
init {
12
6
head.next = tail
@@ -16,17 +10,18 @@ class MyLinkedList() {
16
10
fun get (index : Int ): Int {
17
11
var current = head.next
18
12
var i = 0
19
- while ( current != null && i != index) {
13
+ while ( current != null && i != index) {
20
14
current = current.next
21
15
i++
22
16
}
23
- return if (current != null && current != tail) current.`val ` else - 1
17
+
18
+ return if (current != null && current != tail) current.`val ` else - 1
24
19
}
25
20
26
- fun addAtHead (`val `: Int ) {
21
+ fun addAtHead (`val `: Int ) {
27
22
val prev = head
28
23
val next = head.next
29
- val new = ListNode (`val `)
24
+ val new = LN (`val `)
30
25
31
26
head.next = new
32
27
new.prev = head
@@ -37,7 +32,7 @@ class MyLinkedList() {
37
32
fun addAtTail (`val `: Int ) {
38
33
val next = tail
39
34
val prev = tail.prev
40
- val new = ListNode (`val `)
35
+ val new = LN (`val `)
41
36
42
37
tail.prev = new
43
38
new.prev = prev
@@ -48,13 +43,14 @@ class MyLinkedList() {
48
43
fun addAtIndex (index : Int , `val `: Int ) {
49
44
var current = head.next
50
45
var i = 0
51
- while ( current != null && i != index) {
46
+ while ( current != null && i != index) {
52
47
current = current.next
53
48
i++
54
49
}
55
- if (current != null ) {
50
+
51
+ if (current != null ) {
56
52
val prev = current.prev
57
- val new = ListNode (`val `)
53
+ val new = LN (`val `)
58
54
59
55
prev?.next = new
60
56
new.prev = prev
@@ -66,27 +62,23 @@ class MyLinkedList() {
66
62
fun deleteAtIndex (index : Int ) {
67
63
var current = head.next
68
64
var i = 0
69
- while ( current != null && i != index) {
65
+ while ( current != null && i != index) {
70
66
current = current.next
71
67
i++
72
68
}
73
- if (current != null && current != tail) {
69
+
70
+ if (current != null && current != tail) {
74
71
val prev = current.prev
75
72
val next = current.next
76
73
77
74
prev?.next = next
78
75
next?.prev = prev
79
76
}
80
77
}
81
-
82
78
}
83
79
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
- */
80
+ class LN (
81
+ var `val `: Int ,
82
+ var next : LN ? = null ,
83
+ var prev : LN ? = null
84
+ )
0 commit comments