Share my accepted Java solution!


  • 0
    I
    public class Solution {
        public ListNode removeElements(ListNode head, int val) {
            ListNode dummy = new ListNode(0);
            dummy.next = head;
            ListNode current = dummy;
            while(current.next != null) {
                if (current.next.val == val) {
                    current.next = current.next.next;
                } else {
                    current = current.next;
                }
            }
            return dummy.next;
        }
    }

  • 0
    W

    yeah, good solution for add a external head node.


  • 0
    B

    I tried "return head" instead of the dummy.next but failed, why?


Log in to reply
 

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