添加 707设计链表 Kotlin实现

This commit is contained in:
wz-mibookwindows
2021-08-07 10:55:06 +08:00
parent cb16c9fe18
commit cb65921f6c

View File

@ -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--
}
}
```