mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-07 15:45:40 +08:00
优化 707设计链表 addAtIndex
This commit is contained in:
@ -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++
|
||||
}
|
||||
|
||||
|
Reference in New Issue
Block a user