Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: DSA in Java
Stage 5: Specialization

Part 16 / Topic 4 of 12

Deque as a stack and as a queue

java.util.Deque ("deck," double-ended queue) gives you both a stack (LIFO: last in, first out — push/pop/peek at one end) and a queue (FIFO: first in, first out — offer/poll/peek) from the same class. java.util.Stack still exists but is legacy (synchronized, slower, and the JDK's own Javadoc says to prefer Deque); LinkedList can act as both too, but ArrayDeque is the faster, allocation-cheaper choice for either role in new code. Think of a stack of plates (you only ever take the top one) versus a queue at a ticket counter (first person in line is served first) — same deque class, two different ends used.

Deque<String> callStack = new ArrayDeque<>();
callStack.push("main()");
callStack.push("placeOrder()");
callStack.push("validatePincode()");
// ... callStack.pop() removes "validatePincode()" first: LIFO

Deque<String> printQueue = new ArrayDeque<>();
printQueue.offer("invoice-101.pdf");
printQueue.offer("invoice-102.pdf");
// ... printQueue.poll() removes "invoice-101.pdf" first: FIFO
$ javac DequeDemo.java
$ java DequeDemo
-- Deque as a stack (LIFO) --
stack, top to bottom: [validatePincode(), placeOrder(), main()]
peek (top, not removed): validatePincode()
pop: validatePincode()
after pop: [placeOrder(), main()]

-- Deque as a queue (FIFO) --
queue, head to tail: [invoice-101.pdf, invoice-102.pdf, invoice-103.pdf]
peek (head, not removed): invoice-101.pdf
poll: invoice-101.pdf
after poll: [invoice-102.pdf, invoice-103.pdf]

-- balanced brackets, using a stack --
{"city":["Pune","Delhi"]} -> true
{"city":["Pune"} -> false

-- sliding window maximum, using Deque at both ends --
weights: [4, 8, 2, 9, 5, 7, 1]
max of every window of 3: [8, 9, 9, 9, 7]

Balanced brackets is the canonical stack problem: push every opening bracket, and on every closing bracket, pop and check it matches — an unmatched or leftover bracket means the stack is non-empty or popped from empty at the wrong time. The sliding-window maximum at the end uses both ends of the same deque at once: old, now-out-of-window indices drop off the front, and indices whose value can never be the window's max again (because a bigger value just arrived) drop off the back — the front of the deque is always the current window's maximum.

Full program: examples/stacks-queues/DequeDemo.java.

Real-world build 1: an undo button

Every text editor's undo button is two stacks: an undo stack of actions already applied, and a redo stack of actions just undone. Undo pops the most recent action, reverses it on the document, and pushes the original action onto the redo stack (not its reverse — redo needs to replay the original, not reverse the reversal). Typing anything new clears the redo stack, because the old "future" no longer exists once you've branched off into a new one.

boolean undo() {
    if (undoStack.isEmpty()) return false;
    Action last = undoStack.pop();
    last.inverse().apply();   // cancel the action out on the document
    redoStack.push(last);     // remember the ORIGINAL action, to redo it later
    return true;
}

boolean redo() {
    if (redoStack.isEmpty()) return false;
    Action last = redoStack.pop();
    last.apply();             // re-apply the original action, exactly as it ran the first time
    undoStack.push(last);
    return true;
}
$ javac UndoButtonDemo.java
$ java UndoButtonDemo
after type "Buy milk":        "Buy milk"
after type ", eggs":          "Buy milk, eggs"
after type ", bread":         "Buy milk, eggs, bread"
after 1 undo:                 "Buy milk, eggs"
after 2 undos:                "Buy milk"
after 1 redo:                  "Buy milk, eggs"
after typing "!" (new action): "Buy milk, eggs!"
redo after a new action: false (the ", bread" redo was discarded)
after undoing everything:     ""

Notice typing "!" after undoing twice does not bring back ", bread" on a later redo — redoStack.clear() runs the moment any fresh action is typed, which is exactly the behaviour every editor's undo button has trained you to expect, now visible as two Deques.

Full program: examples/stacks-queues/UndoButtonDemo.java.

Done here? The practice set for Part 16 — including the solutions — is on the part page.

Search the guide