Java accepted code using pre_node


  • 0
    X
     public ListNode removeElements(ListNode head, int val) {
        ListNode init_node = head;
        ListNode pre_node = head;
        if(head == null) return null;
        
        while(head.val == val){
            if(head.next == null) return null;
            else init_node = pre_node = head = head.next;
        }
        
        while(head.next != null){
            if(head.val == val){
                if(head == init_node) init_node = head.next;
                else {
                    pre_node.next = head.next;
                    head = head.next;
                }
            }
            else {
                pre_node = head;
                head = head.next;
            }
        }
        if(head.val == val) pre_node.next = null;
        
        return init_node;
    }

Log in to reply
 

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