From c7c52f7db6d92800a273057c3a5abc4cffcc8aef Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=9E=81=E5=AE=A2=E5=AD=A6=E4=BC=9F?= Date: Mon, 16 Aug 2021 20:28:38 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=20707.=E8=AE=BE=E8=AE=A1?= =?UTF-8?q?=E9=93=BE=E8=A1=A8=20Swift=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0707.设计链表.md | 64 +++++++++++++++++++++++++++++++++++ 1 file changed, 64 insertions(+) diff --git a/problems/0707.设计链表.md b/problems/0707.设计链表.md index 0aa038e8..33b02e56 100644 --- a/problems/0707.设计链表.md +++ b/problems/0707.设计链表.md @@ -948,6 +948,70 @@ class MyLinkedList { } ``` +Swift +```Swift +class MyLinkedList { + var size = 0 + let head: ListNode + + /** Initialize your data structure here. */ + init() { + head = ListNode(-1) + } + + /** Get the value of the index-th node in the linked list. If the index is invalid, return -1. */ + func get(_ index: Int) -> Int { + if size > 0 && index < size { + var tempHead = head + for _ in 0.. size { + return + } + let idx = (index >= 0 ? index : 0) + var tempHead = head + for _ in 0 ..< idx { + tempHead = tempHead.next! + } + let currentNode = tempHead.next + let newNode = ListNode(val, currentNode) + tempHead.next = newNode + size += 1 + } + + /** Delete the index-th node in the linked list, if the index is valid. */ + func deleteAtIndex(_ index: Int) { + if size > 0 && index < size { + var tempHead = head + for _ in 0 ..< index { + tempHead = tempHead.next! + } + tempHead.next = tempHead.next!.next + size -= 1 + } + } +} +``` -----------------------