Share my simple Java AC Solution with dummy


  • 0
    X
    public class Solution {
    public ListNode removeElements(ListNode head, int val) {
    ListNode dummy = new ListNode(0); // create a dummy node to mark the head of this list
    dummy.next = head;
    ListNode pre = dummy; // make a pointer pre as a marker for the node before reversing
    ListNode node=head;
    while (node!=null){
        if(node.val==val){
            pre.next=node.next;
            node=node.next;
        }
        else{
            pre=pre.next;
            node=node.next;
        }
    }
    return dummy.next;
    }
    

    }


Log in to reply
 

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