优化 707设计链表 addAtIndex

This commit is contained in:
wz-mibookwindows
2021-08-07 11:04:11 +08:00
parent cb65921f6c
commit 91c6ecdee9

View File

@ -917,16 +917,17 @@ class MyLinkedList {
}
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) {
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
cur?.next = ListNode(`val`)
cur?.next?.next = temp
this.next = pre.next
size++
}