00:00

Difference between Stack and Queue

Last updated:

Stacks and queues both hold elements in a line and both offer O(1) insertion and removal. The difference lies in which element comes out next: the newest one for a stack, the oldest one for a queue. This page defines each structure and then compares them side by side.

What is a Stack Data Structure?

A stack is a linear data structure in which elements are added and removed at the same end, the top. It follows LIFO order (Last In, First Out): the element pushed most recently is the first one popped.

Stacks suit work that has to be undone or finished in reverse order: method calls, undo/redo, bracket matching, expression parsing and backtracking.

What is a Queue Data Structure?

A queue is a linear data structure in which elements are added at one end, the rear (or tail), and removed from the other end, the front (or head). It follows FIFO order (First In, First Out): elements leave in the same order in which they arrived, like people in a line.

Queues suit work that must be handled in arrival order: task scheduling, message processing, buffering and breadth-first search.

Queue: elements are added at the rear and removed from the front

Difference between Stack and Queue Data Structure

CharacteristicStackQueue
Order of removalLIFO (Last In, First Out): the most recently added element leaves first.FIFO (First In, First Out): the element that has waited longest leaves first.
Ends usedOne end, the top, for both adding and removing.Two ends: add at the rear, remove from the front.
Basic operationspush(), pop(), peek()enqueue(), dequeue(), peek()/front(); some implementations also offer rear()
Time complexitypush, pop and peek: O(1)enqueue, dequeue and peek: O(1) (with a circular array or a linked list with head and tail)
References to trackOne: top.Two: front and rear.
Full condition (fixed array)top == capacity - 1In a simple array queue, rear == capacity - 1; in a circular queue, the element count equals the capacity.
Empty condition (fixed array)top == -1No elements between front and rear (for example, size == 0).
ImplementationArray or linked list.Array (usually circular), linked list, or two stacks.
Java classesDeque<E> (ArrayDeque) with push/pop/peek; the legacy java.util.Stack.Queue<E> (ArrayDeque, LinkedList) with offer/poll/peek.
Typical usesMethod calls, undo, bracket matching, depth-first search.Task and message queues, printer jobs, breadth-first search.