Courses / Computer Science I
Data Structures

Stacks and Queues

Computer Science I 265 words Free to read

Core Order Structures

Some of the most useful data structures are deliberately restricted, allowing additions and removals only at specific ends. This exact restriction is what makes them powerful.

A stack is a last-in, first-out (LIFO) structure. You push elements onto the top, pop the top element off, and peek to view it without removal. The last item added is always the first one popped, acting just like a physical stack of plates.

A queue is a first-in, first-out (FIFO) structure. You enqueue at the back and dequeue from the front. The first element added is the first one removed, modeling any standard service line.

StructureOrderAdd OperationRemove Operation
StackLIFOpush (top)pop (top)
QueueFIFOenqueue (back)dequeue (front)

Both are Abstract Data Types implemented via arrays or linked lists. When well-implemented, all core operations run in O(1)O(1) time.

The same three items, pushed and enqueued together, come back reversed

Variants and Pitfalls

A common variant is the deque (double-ended queue), which allows adding and removing elements at both ends. This effectively generalizes both stacks and queues into a single flexible structure.

Applications are distinct and widespread:

Common pitfall: Mixing up LIFO and FIFO. A stack always returns the most recently added element, while a queue always returns the oldest. Never expect a queue to act like a stack.

Practise this lesson

The explanation above is free to read. The graded practice for this lesson lives in the Tryals app.

11practice questions
2interactive scenes

Data Structures