https://leetcode-cn.com/problems/remove-linked-list-elements
/// 移除链表中指定值的节点 (循环方式)
func removeElements(_ head: ListNode?, _ val: Int) -> ListNode? {
let fakeHead = ListNode(-1)
fakeHead.next = head
var current: ListNode = fakeHead
while current.next != nil {
if current.next!.val == val {
current.next = current.next?.next
} else {
if let next = current.next {
current = next
}
}
}
return fakeHead.next
}
/// 移除链表中指定值的节点 (递归方式)
func removeElements1(_ head: ListNode?, _ val: Int) -> ListNode? {
guard let head = head else {
return nil
}
head.next = removeElements(head.next, val)
return head.val == val ? head.next : head
}
- 虚拟头结点