More Comparisonbeginner

Stack vs Queue in Data Structure

A stack takes out the newest item first. A queue takes out the oldest item first. Learn the rules, code, uses and common exam questions.

6 min read

Our verdict in 30 seconds

A stack is last in, first out (LIFO). The newest item leaves first. A queue is first in, first out (FIFO). The oldest item leaves first. Use a stack for undo, function calls and matching brackets, and a queue for waiting tasks and breadth-first search.

On This Page

Stack vs queue: a stack gives you the newest item first, and a queue gives you the oldest item first. Picture a pile of plates and a line at a ticket counter. You take the top plate from the pile. You serve the first person in the line.

That one rule explains their names. A stack is LIFO, which means last in, first out. A queue is FIFO, which means first in, first out.

Verdict: stack vs queue difference in one table

Point Stack Queue
Removal rule Last in, first out First in, first out
Open ends One, called the top Two, called front and rear
Add operation Push Enqueue or offer
Remove operation Pop Dequeue or poll
Look without removing Peek Peek or front
Add and remove cost O(1) O(1)
Common use Undo, brackets, DFS Waiting tasks, BFS

If you put in A, then B, then C, a stack returns C, B, A. A queue returns A, B, C. The costs assume a good implementation.

Stack vs queue in data structure: what is allowed?

Both are abstract data types. This means they state the actions and rules, not the exact storage. You can build either one with an array or a linked list.

A stack has one working end:

  • push(x) adds x to the top.
  • pop() removes and returns the top item.
  • peek() returns the top item and leaves it there.
  • isEmpty() tells you if there are no items.

A queue has two working ends:

  • enqueue(x) adds x at the rear.
  • dequeue() removes and returns the front item.
  • peek() returns the front item and leaves it there.
  • isEmpty() tells you if there are no items.

Two error words appear in exams. Overflow means you try to add to a full fixed-size structure. Underflow means you try to remove from an empty one.

Java and Python collections can grow, so they do not have the small fixed limit of a textbook array. Removing from an empty one can still cause an error or return an empty result.

Java example with real output

Java's ArrayDeque can work as a stack or a queue. Deque sounds like "deck" and means double-ended queue.

import java.util.*;

public class StackQueue {
  public static void main(String[] args) {
    Deque<String> stack = new ArrayDeque<>();
    Queue<String> queue = new ArrayDeque<>();
    for (String s : List.of("A", "B", "C")) {
      stack.push(s);
      queue.offer(s);
    }
    System.out.print("Stack:");
    while (!stack.isEmpty()) System.out.print(" " + stack.pop());
    System.out.print("\nQueue:");
    while (!queue.isEmpty()) System.out.print(" " + queue.poll());
    PriorityQueue<Integer> heap =
        new PriorityQueue<>(List.of(30, 10, 20));
    System.out.print("\nHeap:");
    while (!heap.isEmpty()) System.out.print(" " + heap.poll());
    System.out.println();
  }
}

The output is:

Stack: C B A
Queue: A B C
Heap: 10 20 30

The same three letters come out in two different orders. The heap line goes by value, not arrival time. We will come back to it below.

Java has an older Stack class. The Java API suggests using a Deque instead. Note that ArrayDeque does not allow null values.

Common mistake: A common mistake beginners make is to mix up poll and remove in Java. On an empty queue, poll() returns null. remove() throws an exception. Choose the one that fits your program.

Stack vs queue in Python

A Python list works well as a stack because adding and removing at its end is fast.

stack = []
stack.append("A")
stack.append("B")
print(stack.pop())

This prints B, which was added last.

For a queue, use collections.deque:

from collections import deque

queue = deque()
queue.append("A")
queue.append("B")
print(queue.popleft())

This prints A, which was added first.

You could use list.pop(0) for a queue, but every remaining item must shift left. That costs O(n) per removal. A deque removes from either end in O(1) time. If several threads share work, Python's queue.Queue adds the needed locking.

Other Python types have different rules. Read list vs tuple to compare some of them.

Where you use each one

Undo in an editor: Each change goes on a stack. Undo removes the newest change.

Function calls: The computer keeps active calls in a call stack. The newest call must finish before its caller continues.

Matching brackets: Push each opening bracket. When you see a closing bracket, it must match the top. Try this in valid parentheses in Java.

Browser back button: The pages you leave can be kept on a stack. The most recent page comes back first.

Print jobs: A simple printer queue prints jobs in arrival order.

Background work: A web app may put email tasks in a queue. A worker takes the oldest task first. Real systems may also use priorities and retries.

Graph search: BFS uses a queue. DFS uses recursion or a stack. The output of both is shown in BFS vs DFS.

Pro tip: Words such as "undo", "nested" or "most recent" in a problem often point to a stack. Words such as "first come" and "level by level" often point to a queue.

Stack vs queue vs linked list

A linked list is storage. Each node has a value and a link to another node. A stack or queue is a rule about which item you may use.

Point Stack Queue Linked list
What it is LIFO rule FIFO rule Nodes joined by links
Where you may remove Top Front Any node
Search for a value Not its main use Not its main use O(n)
How they relate Can be built with a linked list Can be built with a linked list Can build both

To build a stack from a singly linked list, add and remove at the head. Both are O(1).

To build a queue, keep a head and a tail pointer. Add at the tail and remove at the head. Both are O(1). If you forget the tail pointer, adding may require walking through all nodes.

An array can also store both. A queue built from a plain array must avoid shifting all items. A circular array solves this by moving its front index and wrapping around. To compare storage in more depth, see array vs linked list.

Stack vs queue vs heap

The word heap has two common meanings. It may mean a tree-like data structure. It may also mean the memory area where a program stores objects. This section means the data structure.

A min heap always gives you the smallest value. A max heap gives you the largest. It does not care which item arrived first. In the Java example, PriorityQueue received 30, 10 and 20, then returned 10, 20 and 30.

Structure Next item out Add Remove next
Stack Newest O(1) O(1)
Queue Oldest O(1) O(1)
Binary heap Smallest or largest O(log n) O(log n)

Use a heap when priority matters, such as "treat the most urgent patient first". Use a plain queue for a normal line.

In memory, the call stack holds method calls and the heap holds many objects. That topic is separate from these data structures.

Choose a stack if / Choose a queue if

Choose a stack if:

  • You need the newest item first.
  • You must undo the last action.
  • You are matching nested items.
  • You need to return to the previous state.

Choose a queue if:

  • You need to keep arrival order.
  • Work must wait for a free worker.
  • You are visiting a graph level by level.
  • For a short time, data comes faster than you can process it.

Choose a deque if you must add or remove at both ends.

For freshers: interview practice

Start with the one-line answer: "A stack is LIFO, and a queue is FIFO." Then name one use, one operation and its time cost.

Practise these tasks:

  1. Reverse a string with a stack.
  2. Check balanced brackets.
  3. Make a queue with two stacks.
  4. Make a circular queue with an array.
  5. Print a tree level by level.

Interview note: For a queue using two stacks, explain the cost carefully. One dequeue may take O(n), but each item moves only once. Over many operations, the average cost is O(1). This is called amortized O(1).

Use data structures and algorithms for the bigger plan and DSA interview questions for practice. Write the moves on paper before coding. If you can show what is at the top, front and rear after each step, your code will be much easier.

Frequently Asked Questions

What is the main difference between a stack and a queue?
A stack removes the newest item first, which is LIFO. A queue removes the oldest item first, which is FIFO. Both normally add and remove in O(1) time with a good implementation.
Can a queue be made using two stacks?
Yes. Push new items into the first stack. When the second stack is empty, move all items into it and pop from there. Each item moves at most once, so the average cost per operation over many calls is O(1).
Is a linked list a stack or a queue?
Neither by itself. A linked list is a way to store linked nodes. You can use it to build either one. The stack or queue rule tells you which end may be used.
Why is list.pop(0) slow in Python?
A Python list must shift all later items one place after the first item is removed. That takes O(n) time. Use collections.deque and popleft for a queue.
What is a circular queue?
It is a fixed-size array queue where the end wraps back to the start. This reuses empty spaces left after old items are removed.

Want to Build Your Career in Java Full Stack with AI?

Join CodeBegun and train with working industry engineers — Check the Java Full Stack training details

Apply for Demo Class →
Siva Prasad Galaba
Founder, CodeBegun · Staff Engineer

Founder of CodeBegun. 15+ years building Java systems at companies like Crunchyroll. Teaches Java, Spring Boot and system design the way the industry actually works, and mentors students through projects, mock interviews and placement preparation.

Technically reviewed by CodeBegun Technical TeamLast reviewed 3 December 2026 LinkedIn

More comparisons

View all
Chat with us