Skip to content

Latest commit

 

History

History
executable file
·
42 lines (31 loc) · 916 Bytes

File metadata and controls

executable file
·
42 lines (31 loc) · 916 Bytes

203. 移除链表元素

https://leetcode-cn.com/problems/remove-linked-list-elements

Solution

/// 移除链表中指定值的节点 (循环方式)
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
}

Tip

  • 虚拟头结点