移除链表元素

题目 - Delete Node in a Linked List

LeetCode-203

剑指 Offer 18. 删除链表的节点

难度:简单

分析

递归

迭代

代码

递归实现


func removeElements(_ head: ListNode?, _ val: Int) -> ListNode? {
   if head == nil {
        return head
    }
    
    head?.next = removeElements(head?.next, val)
    if head?.val == val {
        return head?.next
    }
    return head
}

迭代实现

func removeElements(_ head: ListNode?, _ val: Int) -> ListNode? {
    var head = head
    while head != nil && head?.val == val {
        head = head?.next
    }
    if head == nil {
        return head
    }
    var p: ListNode = head!
    while p.next != nil {
        if p.next?.val == val {
            p.next = p.next?.next
        } else {
            p = p.next!
        }
    }
    return head
}