为链表篇 增加 Swift 实现

This commit is contained in:
frank-tian
2021-07-17 22:28:06 +08:00
parent a16c030b44
commit 7b55df11dc
14 changed files with 499 additions and 3 deletions

View File

@@ -165,3 +165,34 @@ class Solution:
return dummy.next # 注意这里传回的不是head而是虚拟节点的下一个节点head有可能已经换了
```
Swift Code
```swift
class Solution {
func deleteDuplicates(_ head: ListNode?) -> ListNode? {
// 侦察兵指针
var pre = head
// 创建哑节点接上head
var dummy = ListNode(-1)
dummy.next = head
// 跟随的指针
var low:ListNode? = dummy
while pre != nil && pre?.next != nil {
if pre?.val == pre?.next?.val {
// 移动侦察兵指针直到找到与上一个不相同的元素
while pre != nil && pre?.next != nil && pre?.val == pre?.next?.val {
pre = pre?.next
}
// while循环后pre停留在最后一个重复的节点上
pre = pre?.next
// 连上新节点
low?.next = pre
} else {
pre = pre?.next
low = low?.next
}
}
return dummy.next // 注意这里传回的不是head而是虚拟节点的下一个节点head有可能已经换了
}
}
```