diff --git a/problems/0707.设计链表.md b/problems/0707.设计链表.md index 349e2409..f7b03c8b 100644 --- a/problems/0707.设计链表.md +++ b/problems/0707.设计链表.md @@ -880,7 +880,72 @@ MyLinkedList.prototype.deleteAtIndex = function(index) { * obj.deleteAtIndex(index) */ ``` +Kotlin: +```kotlin +class MyLinkedList { + var next: ListNode? = null + + var size: Int = 0 + + fun get(index: Int): Int { + if (index + 1 > size) return -1 + var cur = this.next + for (i in 0 until index) { + cur = cur?.next + } + return cur?.`val` ?: -1 + } + + fun addAtHead(`val`: Int) { + val head = ListNode(`val`) + head.next = this.next + this.next = head + size++ + } + + fun addAtTail(`val`: Int) { + val pre = ListNode(0) + pre.next = this.next + var cur: ListNode? = pre + while (cur?.next != null) { + cur = cur.next + } + cur?.next = ListNode(`val`) + this.next = pre.next + size++ + } + + fun addAtIndex(index: Int, `val`: Int) { + if (index == 0) return addAtHead(`val`) + if (index == size) return addAtTail(`val`) + if (index > size) return + var cur = this.next + for (i in 0 until index - 1) { + cur = cur?.next + } + val temp = cur?.next + cur?.next = ListNode(`val`) + cur?.next?.next = temp + size++ + } + + fun deleteAtIndex(index: Int) { + if (index + 1 > size) return + val pre = ListNode(0) + pre.next = this.next + var cur: ListNode? = pre + for (i in 0 until index) { + cur = cur?.next + } + val temp = cur?.next?.next + cur?.next?.next = null + cur?.next = temp + this.next = pre.next + size-- + } +} +```