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

Example

Given: 1 –> 2 –> 6 –> 3 –> 4 –> 5 –> 6, val = 6

Return: 1 –> 2 –> 3 –> 4 –> 5

/**
 Definition for singly-linked list.
 
 public class ListNode {
   int val;
   ListNode next;
   ListNode(int x) { val = x; }
 }
 */
public class Solution {
  public ListNode removeElements(ListNode head, int val) {

  }
}

This problem is selected from LeetCode.

Solution

Traverse the list node by node and remove the nodes with values of the target value. Be careful to the following:

1, When the head needs to be removed.

2, When continuous nodes need to be removed.

3. When the whole list needs to be removed.

4. When the last node needs to be removed.

public class Solution {
  public ListNode removeElements(ListNode head, int val) {
      
    // handle the cases when the head 
    // needs to be removed. 
    // move head to the first node that
    // has a different value.
    while(head != null && head.val == val)
      head = head.next;
    
    // when the whole list is deleted, the
    // head is null, so just return null.
    if(head == null) 
      return null;
    
    ListNode current = head;
    while(current != null) {
      
      ListNode temp = current.next;
      
      // remove continuous nodes with the value.
      while(temp != null && temp.val == val) {
          temp = temp.next;
      }
      
      current.next = temp;
      current = current.next;
    }
    
    return head;
  }
}

RelatedPost