Easy java solution (using a head node trick)


  • 1
    N
    public class Solution {
    public ListNode removeElements(ListNode head, int val) {
        
        /*Trick:
         *using a headnode , headnode's next always point to the real head
         *headnode don't save data, but it can simplify the delete operation
         */
        ListNode headNode = new ListNode(0); 
        headNode.next = head;
        
        ListNode pre = headNode;
        
        while(head != null){
            
            if(head.val == val)
                pre.next = head.next ; //remove element
            else
                pre=pre.next;
    
            head = head.next; //move to next
        }
        
        return headNode.next;
        
    }
    

    }


  • 0
    O

    please tell me why didnt the headNode changed when you changed the pre ?? Arent both of them pointing to the same reference ?? so when you change one of them the other should automatically change too ??


  • 0
    T

    No, they do not really point to the same reference. Only pre points to headNode. When you set pre to a new reference, headNode still points to the old reference.


Log in to reply
 

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