mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 03:34:02 +08:00
优化 707设计链表 addAtIndex
This commit is contained in:
@ -917,16 +917,17 @@ class MyLinkedList {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fun addAtIndex(index: Int, `val`: Int) {
|
fun addAtIndex(index: Int, `val`: Int) {
|
||||||
if (index == 0) return addAtHead(`val`)
|
|
||||||
if (index == size) return addAtTail(`val`)
|
|
||||||
if (index > size) return
|
if (index > size) return
|
||||||
var cur = this.next
|
val pre = ListNode(0)
|
||||||
for (i in 0 until index - 1) {
|
pre.next = this.next
|
||||||
|
var cur:ListNode? = pre
|
||||||
|
for (i in 0 until index) {
|
||||||
cur = cur?.next
|
cur = cur?.next
|
||||||
}
|
}
|
||||||
val temp = cur?.next
|
val temp = cur?.next
|
||||||
cur?.next = ListNode(`val`)
|
cur?.next = ListNode(`val`)
|
||||||
cur?.next?.next = temp
|
cur?.next?.next = temp
|
||||||
|
this.next = pre.next
|
||||||
size++
|
size++
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Reference in New Issue
Block a user