From 91c6ecdee95f5eb97b53590a81e242ef6d5f75c7 Mon Sep 17 00:00:00 2001 From: wz-mibookwindows Date: Sat, 7 Aug 2021 11:04:11 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BC=98=E5=8C=96=20707=E8=AE=BE=E8=AE=A1?= =?UTF-8?q?=E9=93=BE=E8=A1=A8=20addAtIndex?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0707.设计链表.md | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/problems/0707.设计链表.md b/problems/0707.设计链表.md index f7b03c8b..5e748a24 100644 --- a/problems/0707.设计链表.md +++ b/problems/0707.设计链表.md @@ -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++ }