Easy to understand with Stack


  • 0
    X

    It's good to understand when you use stack.

    public ListNode deleteDuplicates(ListNode head) {
            Stack<ListNode> stack = new Stack<>();
            ListNode cur = head;
            boolean pop = false;
            while (cur != null) {
                if (!stack.isEmpty() && stack.peek().val == cur.val){
                    pop = true;
                }else {
                    if (pop){
                        stack.pop();
                        pop = false;
                    }
                    stack.push(cur);
                }
                cur = cur.next;
            }
            if (pop) stack.pop();
            head = null;
            while (!stack.empty()){
                cur = stack.pop();
                cur.next = head;
                head = cur;
            }
            return head;
        }
    

Log in to reply
 

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