Skip to content

Commit c7c52f7

Browse files
author
极客学伟
committed
添加 707.设计链表 Swift版本
1 parent 07e95e7 commit c7c52f7

File tree

1 file changed

+64
-0
lines changed

1 file changed

+64
-0
lines changed

problems/0707.设计链表.md

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -948,6 +948,70 @@ class MyLinkedList {
948948
}
949949
```
950950

951+
Swift
952+
```Swift
953+
class MyLinkedList {
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+
func get(_ index: Int) -> Int {
964+
if size > 0 && index < size {
965+
var tempHead = head
966+
for _ in 0..<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+
func addAtHead(_ val: Int) {
978+
addAtIndex(0, val)
979+
}
980+
981+
/** Append a node of value val to the last element of the linked list. */
982+
func addAtTail(_ 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+
func addAtIndex(_ index: Int, _ val: Int) {
988+
if index > size {
989+
return
990+
}
991+
let idx = (index >= 0 ? index : 0)
992+
var tempHead = head
993+
for _ in 0 ..< 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. */
1003+
func deleteAtIndex(_ index: Int) {
1004+
if size > 0 && index < size {
1005+
var tempHead = head
1006+
for _ in 0 ..< index {
1007+
tempHead = tempHead.next!
1008+
}
1009+
tempHead.next = tempHead.next!.next
1010+
size -= 1
1011+
}
1012+
}
1013+
}
1014+
```
9511015

9521016

9531017
-----------------------

0 commit comments

Comments
 (0)