203. Remove Linked List Elements

2019/10/21 Leetcode

203. Remove Linked List Elements

Tags: ‘Linked List’

Remove all elements from a linked list of integers that have value val.

Example:

Input:  1->2->6->3->4->5->6, val = 6
Output: 1->2->3->4->5

Solution

Mind corner cases. 遇事不决画个图

public ListNode removeElements(ListNode head, int val) {
    if (head == null) return null;
    ListNode dummy = new ListNode(-1);
    dummy.next = head;
    
    ListNode curr = head, prev = dummy;
    while (curr != null) {
        if (curr.val == val) {
            prev.next = curr.next;
            curr = curr.next;
        } else {
            prev = prev.next;
            curr = curr.next;
        }
    }
    return dummy.next;
}

Search

    Table of Contents

    文章目录