You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: problems/0707.设计链表.md
+64Lines changed: 64 additions & 0 deletions
Original file line number
Diff line number
Diff line change
@@ -948,6 +948,70 @@ class MyLinkedList {
948
948
}
949
949
```
950
950
951
+
Swift
952
+
```Swift
953
+
classMyLinkedList {
954
+
var size =0
955
+
let head: ListNode
956
+
957
+
/** Initialize your data structure here. */
958
+
init() {
959
+
head =ListNode(-1)
960
+
}
961
+
962
+
/** Get the value of the index-th node in the linked list. If the index is invalid, return -1. */
963
+
funcget(_index: Int) ->Int {
964
+
if size >0&& index < size {
965
+
var tempHead = head
966
+
for_in0..<index {
967
+
tempHead = tempHead.next!
968
+
}
969
+
let currentNode = tempHead.next!
970
+
return currentNode.val
971
+
} else {
972
+
return-1
973
+
}
974
+
}
975
+
976
+
/** Add a node of value val before the first element of the linked list. After the insertion, the new node will be the first node of the linked list. */
977
+
funcaddAtHead(_val: Int) {
978
+
addAtIndex(0, val)
979
+
}
980
+
981
+
/** Append a node of value val to the last element of the linked list. */
982
+
funcaddAtTail(_val: Int) {
983
+
addAtIndex(size, val)
984
+
}
985
+
986
+
/** Add a node of value val before the index-th node in the linked list. If index equals to the length of linked list, the node will be appended to the end of linked list. If index is greater than the length, the node will not be inserted. */
987
+
funcaddAtIndex(_index: Int, _val: Int) {
988
+
if index > size {
989
+
return
990
+
}
991
+
let idx = (index >=0? index :0)
992
+
var tempHead = head
993
+
for_in0..< idx {
994
+
tempHead = tempHead.next!
995
+
}
996
+
let currentNode = tempHead.next
997
+
let newNode =ListNode(val, currentNode)
998
+
tempHead.next= newNode
999
+
size +=1
1000
+
}
1001
+
1002
+
/** Delete the index-th node in the linked list, if the index is valid. */
0 commit comments