Java iterative solution with dummy head


  • 0
    J
    public class Solution {
    public ListNode removeElements(ListNode head, int val) {
        if(head == null) {
            return null;
        }
    
        final ListNode dummyHead = new ListNode(0);
        ListNode prev = dummyHead;
        ListNode node = head;
        
        while(node != null) {
            if(node.val != val) {
                prev.next = node;
                prev = prev.next;
            }
            node = node.next;
        }
        prev.next = null;
        return dummyHead.next;
    }
    

    }


Log in to reply
 

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