11class 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 )
104
115 init {
126 head.next = tail
@@ -16,17 +10,18 @@ class MyLinkedList() {
1610 fun get (index : Int ): Int {
1711 var current = head.next
1812 var i = 0
19- while ( current != null && i != index) {
13+ while ( current != null && i != index) {
2014 current = current.next
2115 i++
2216 }
23- return if (current != null && current != tail) current.`val ` else - 1
17+
18+ return if (current != null && current != tail) current.`val ` else - 1
2419 }
2520
26- fun addAtHead (`val `: Int ) {
21+ fun addAtHead (`val `: Int ) {
2722 val prev = head
2823 val next = head.next
29- val new = ListNode (`val `)
24+ val new = LN (`val `)
3025
3126 head.next = new
3227 new.prev = head
@@ -37,7 +32,7 @@ class MyLinkedList() {
3732 fun addAtTail (`val `: Int ) {
3833 val next = tail
3934 val prev = tail.prev
40- val new = ListNode (`val `)
35+ val new = LN (`val `)
4136
4237 tail.prev = new
4338 new.prev = prev
@@ -48,13 +43,14 @@ class MyLinkedList() {
4843 fun addAtIndex (index : Int , `val `: Int ) {
4944 var current = head.next
5045 var i = 0
51- while ( current != null && i != index) {
46+ while ( current != null && i != index) {
5247 current = current.next
5348 i++
5449 }
55- if (current != null ) {
50+
51+ if (current != null ) {
5652 val prev = current.prev
57- val new = ListNode (`val `)
53+ val new = LN (`val `)
5854
5955 prev?.next = new
6056 new.prev = prev
@@ -66,27 +62,23 @@ class MyLinkedList() {
6662 fun deleteAtIndex (index : Int ) {
6763 var current = head.next
6864 var i = 0
69- while ( current != null && i != index) {
65+ while ( current != null && i != index) {
7066 current = current.next
7167 i++
7268 }
73- if (current != null && current != tail) {
69+
70+ if (current != null && current != tail) {
7471 val prev = current.prev
7572 val next = current.next
7673
7774 prev?.next = next
7875 next?.prev = prev
7976 }
8077 }
81-
8278}
8379
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