LeetCode - Remove Linked List Elements

less than 1 minute read

Problem description

description

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

Example:

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

Analysis

This is a simple problem. The only two things need to be watch out is remove the first item of the linked list and remove two consecutive item. Thus we need a dummy node and if it matches we should not move forward.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public ListNode removeElements(ListNode head, int val) {
        ListNode dummy = new ListNode(0);
        
        dummy.next = head;
        
        ListNode p = dummy;
        
        while(p!= null && p.next != null){
            if (p.next.val == val){
                p.next = p.next.next;
            }
            // here needs a else
            else {
                p = p.next;
            }
        }
        
        return dummy.next;
        
    }

What to improve

  • linked list should not move forward if there’s a match