mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 03:34:02 +08:00
添加0707.设计链表 Swift版本
This commit is contained in:
@ -948,6 +948,87 @@ class MyLinkedList {
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
Swift:
|
||||||
|
|
||||||
|
```swift
|
||||||
|
class MyLinkedList {
|
||||||
|
var dummyHead: ListNode<Int>?
|
||||||
|
var size: Int
|
||||||
|
|
||||||
|
init() {
|
||||||
|
dummyHead = ListNode(0)
|
||||||
|
size = 0
|
||||||
|
}
|
||||||
|
|
||||||
|
func get(_ index: Int) -> Int {
|
||||||
|
if index >= size || index < 0 {
|
||||||
|
return -1
|
||||||
|
}
|
||||||
|
|
||||||
|
var curNode = dummyHead?.next
|
||||||
|
var curIndex = index
|
||||||
|
|
||||||
|
while curIndex > 0 {
|
||||||
|
curNode = curNode?.next
|
||||||
|
curIndex -= 1
|
||||||
|
}
|
||||||
|
|
||||||
|
return curNode?.value ?? -1
|
||||||
|
}
|
||||||
|
|
||||||
|
func addAtHead(_ val: Int) {
|
||||||
|
let newHead = ListNode(val)
|
||||||
|
newHead.next = dummyHead?.next
|
||||||
|
dummyHead?.next = newHead
|
||||||
|
size += 1
|
||||||
|
}
|
||||||
|
|
||||||
|
func addAtTail(_ val: Int) {
|
||||||
|
let newNode = ListNode(val)
|
||||||
|
var curNode = dummyHead
|
||||||
|
while curNode?.next != nil {
|
||||||
|
curNode = curNode?.next
|
||||||
|
}
|
||||||
|
|
||||||
|
curNode?.next = newNode
|
||||||
|
size += 1
|
||||||
|
}
|
||||||
|
|
||||||
|
func addAtIndex(_ index: Int, _ val: Int) {
|
||||||
|
if index > size {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
let newNode = ListNode(val)
|
||||||
|
var curNode = dummyHead
|
||||||
|
var curIndex = index
|
||||||
|
|
||||||
|
while curIndex > 0 {
|
||||||
|
curNode = curNode?.next
|
||||||
|
curIndex -= 1
|
||||||
|
}
|
||||||
|
|
||||||
|
newNode.next = curNode?.next
|
||||||
|
curNode?.next = newNode
|
||||||
|
size += 1
|
||||||
|
}
|
||||||
|
|
||||||
|
func deleteAtIndex(_ index: Int) {
|
||||||
|
if index >= size || index < 0 {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
var curNode = dummyHead
|
||||||
|
for _ in 0..<index {
|
||||||
|
curNode = curNode?.next
|
||||||
|
}
|
||||||
|
|
||||||
|
curNode?.next = curNode?.next?.next
|
||||||
|
size -= 1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
-----------------------
|
-----------------------
|
||||||
|
Reference in New Issue
Block a user