Merge pull request #615 from qxuewei/master

添加 203.移除链表元素 Swift版本
This commit is contained in:
程序员Carl
2021-08-19 10:28:59 +08:00
committed by GitHub
3 changed files with 102 additions and 2 deletions

View File

@ -304,8 +304,7 @@ var removeElements = function(head, val) {
};
```
Swift:
Swift
```swift
/**
* Definition for singly-linked list.

View File

@ -334,6 +334,43 @@ fun reverseList(head: ListNode?): ListNode? {
}
```
Swift
```swift
/// 双指针法 (迭代)
/// - Parameter head: 头结点
/// - Returns: 翻转后的链表头结点
func reverseList(_ head: ListNode?) -> ListNode? {
if head == nil || head?.next == nil {
return head
}
var pre: ListNode? = nil
var cur: ListNode? = head
var temp: ListNode? = nil
while cur != nil {
temp = cur?.next
cur?.next = pre
pre = cur
cur = temp
}
return pre
}
/// 递归
/// - Parameter head: 头结点
/// - Returns: 翻转后的链表头结点
func reverseList2(_ head: ListNode?) -> ListNode? {
return reverse(pre: nil, cur: head)
}
func reverse(pre: ListNode?, cur: ListNode?) -> ListNode? {
if cur == nil {
return pre
}
let temp: ListNode? = cur?.next
cur?.next = pre
return reverse(pre: cur, cur: temp)
}
```
-----------------------
* 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw)
* B站视频[代码随想录](https://space.bilibili.com/525438321)

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
}
}
}
```
-----------------------