My Java Solution


  • 0

    My solution is not very efficient, but I post it just to share with others, perhaps other people here could help me to refine it...

    public ListNode removeElements(ListNode head, int val) {
            if(head==null){
                return null;
            }
            ListNode start = new ListNode(0);
            start.next = head;
            ListNode cur = start;
            ListNode cur2 =start.next;
            boolean find = false;
            while(cur2!=null){
                if(cur!=null&&cur.next.val==val){
                    find = true;
                }
                if(find&&cur2.val!=val){
                    cur.next = cur2;
                    cur = cur2;
                    find = false;
                    cur2 = cur2.next;
                    continue;
                }
                if(cur.next!=null&&cur.next.val!=val){
                    cur = cur.next;
                }
                cur2 = cur2.next;
            }
            cur.next = cur2;
            return start.next;
        }
    

Log in to reply
 

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