Simple Java Solution


  • 0
    C

    Accepted solution, time complexity O(n)

    public ListNode removeElements(ListNode head, int val) {
            ListNode pre = null;
            ListNode cur = head;
            while(cur != null) {
                if(cur.val == val) {
                    if(pre != null) {
                        pre.next = cur.next;
                    } else {
                        head = cur.next;
                        pre = null;
                    }
                } else {
                    pre = cur;
                }
                cur = cur.next;
            }
            return head;
        }
    

Log in to reply
 

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