Accepted clean Java solution


  • 1

    A fake head can help us solve this problem easily.

    public ListNode removeElements(ListNode head, int val) {
      ListNode l = new ListNode(0), p = l;
      
      while (head != null) {
        if (head.val != val) {
          p.next = head;
          p = p.next;
        }
        head = head.next;
      }
      
      p.next = null;
      
      return l.next;
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.