添加 707.设计链表 Swift版本

This commit is contained in:
极客学伟
2021-08-16 20:28:38 +08:00
parent 07e95e7a97
commit c7c52f7db6

View File

@ -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..<index {
tempHead = tempHead.next!
}
let currentNode = tempHead.next!
return currentNode.val
} else {
return -1
}
}
/** 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. */
func addAtHead(_ val: Int) {
addAtIndex(0, val)
}
/** Append a node of value val to the last element of the linked list. */
func addAtTail(_ val: Int) {
addAtIndex(size, val)
}
/** 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. */
func addAtIndex(_ index: Int, _ val: Int) {
if index > 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
}
}
}
```
-----------------------