Simple java solution


  • 0
    L
    public class Solution {
        public ListNode removeElements(ListNode head, int val) {
            if(head==null){
                return head;
            }
            while(head!=null && head.val==val){
                head=head.next;
            }
            ListNode temp = head;
            while(temp!=null){
                ListNode temp2=temp.next;
                while(temp2!=null && temp2.val==val){
                    temp2=temp2.next;
                }
                temp.next = temp2;
                temp = temp.next;
            }
            return head;
        }
    }
    

  • 0
    S

    Question. Why not use only one temp instead of two?

    You only need to know the current node you are on and then check if next one needs to be removed or not.

    If the next node is fine as it is and not null you move over to that node.


Log in to reply
 

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