Stacks and Queues Explained With Examples
SkillVeris Team
Engineering Team

A stack is last-in first-out: the most recently added item is the first one removed, like a pile of plates.
In this guide, you'll learn:
- A queue is first-in first-out: items leave in the order they arrived, like a line at a checkout.
- Both offer constant-time additions and removals, which makes them fast building blocks for larger algorithms.
- Stacks power function calls, undo features, and expression parsing, while queues power scheduling, buffering, and breadth-first search.
1What Are Stacks And Queues
Stacks and queues are two of the simplest and most useful data structures, and they differ in one essential way: the order in which items leave. A stack removes the most recently added item first, a policy called last-in first-out. A queue removes the oldest item first, a policy called first-in first-out. Everything else about them follows from that single rule.
Both structures restrict how you access their contents. Unlike an array where you can read any position, a stack and a queue only let you add and remove from specific ends. This restriction is a feature, not a limitation, because it makes their behavior predictable and their operations extremely fast.
Understanding these two structures deeply pays off because they appear inside countless algorithms and systems. Many problems become easy the moment you recognize that a stack or a queue is the right tool, and the two even define the difference between depth-first and breadth-first graph traversal.
They are also among the first structures where you feel the value of choosing the right abstraction. Rather than juggling raw arrays and manual index bookkeeping, you work with a small, meaningful vocabulary of operations that matches how you think about the problem. That clarity reduces bugs and makes your intent obvious to anyone reading your code later.
2How A Stack Works
A stack behaves like a pile of plates. You add a new plate to the top, and when you need one, you take from the top. You never pull from the middle or the bottom. The two core operations are push, which adds an item to the top, and pop, which removes and returns the top item. A third operation, peek, lets you look at the top without removing it.
Because all activity happens at one end, a stack always removes the most recently added item first. This is why it is called last-in first-out. If you push the numbers one, two, and three in that order, popping returns three, then two, then one, exactly reversing the order of insertion.
Stacks are often implemented on top of an array or a linked list. With either, push and pop happen in constant time because they touch only the top. That speed, combined with the simple mental model, makes stacks a favorite building block.
3How A Queue Works
A queue behaves like a line of people at a counter. New arrivals join the back, and service happens at the front, so whoever arrived first is served first. The two core operations are enqueue, which adds an item to the back, and dequeue, which removes and returns the item at the front. A peek operation shows the front item without removing it.
Because additions and removals happen at opposite ends, a queue always removes the oldest item first, which is the first-in first-out policy. If you enqueue one, two, and three, dequeuing returns one, then two, then three, preserving the original order rather than reversing it.
Implementing a queue efficiently requires a little care so that both ends support fast operations. A naive array where you remove from the front by shifting every element is slow. Using a linked list, a circular buffer, or two coordinated stacks keeps both enqueue and dequeue constant time.
4The Core Operations Compared
Both structures share a similar tiny interface, which is part of their appeal. A stack offers push, pop, peek, and usually a check for whether it is empty. A queue offers enqueue, dequeue, peek, and an empty check. Keeping these operations minimal is deliberate, because the restricted interface is what gives each structure its guarantees.
The key difference is purely about which end you remove from. A stack adds and removes at the same end. A queue adds at one end and removes from the other. That one design decision produces two completely different behaviors and suits two completely different families of problems.
It is worth noting what these structures deliberately do not offer. You cannot ask a stack or a queue for the item in the middle, nor search them efficiently for an arbitrary value. If you need that kind of access, a different structure like an array or a hash table is appropriate. The narrow interface is the whole point, and trying to work around it usually signals that you have chosen the wrong tool.
5Performance Characteristics
Both stacks and queues provide constant-time additions and removals when implemented well, meaning the cost does not grow as the structure gets larger. This predictable speed is one of the main reasons they are so widely used inside performance-sensitive algorithms.
Their space usage grows in direct proportion to the number of items they hold, which is the minimum any structure could require. There is no hidden overhead beyond the elements themselves and a small amount of bookkeeping. This combination of fast operations and lean memory makes them ideal low-level building blocks.
6Where Stacks Are Used
Stacks are behind more of your daily computing than you might guess. Every time a program calls a function, the computer pushes information about that call onto a call stack, and when the function returns, it pops back off. This is what allows nested and recursive function calls to unwind correctly in reverse order.
The undo feature in editors relies on a stack: each action is pushed on, and undo pops the most recent one. Web browsers use a stack for the back button, returning to the most recently visited page first. Stacks also parse and evaluate expressions, matching parentheses and converting between notation styles, because the last-opened bracket should be the first one closed.
In graph algorithms, a stack drives depth-first search, pushing nodes to explore and popping to dive deeper before backtracking. Recognizing a last-in first-out pattern in a problem is a strong hint that a stack is the tool you need.
7Where Queues Are Used
Queues shine whenever items must be handled in the order they arrive. Operating systems use queues to schedule tasks and manage requests fairly, serving the earliest waiting job first. Printers hold documents in a queue so they print in submission order. Network systems buffer incoming data in queues to smooth out bursts.
Queues also power breadth-first search in graphs, processing nearer nodes before farther ones to guarantee shortest paths in unweighted graphs. Message systems between programs pass work through queues so producers and consumers can operate at their own pace. Whenever fairness or arrival order matters, a queue is usually the answer.
8Choosing Between A Stack And A Queue
The decision between the two comes down to a single question: do you want the most recent item or the oldest item next? If the answer is most recent, you want a stack and its last-in first-out behavior. If the answer is oldest, you want a queue and its first-in first-out behavior. Framing the problem in those terms usually makes the choice obvious.
This distinction is exactly what separates depth-first search from breadth-first search on a graph. Swap the stack in DFS for a queue and you get BFS, without changing anything else about the traversal. That small substitution changing the entire character of the algorithm is a striking demonstration of how much the ordering policy matters, and it is a useful mental checkpoint whenever you are unsure which structure a problem needs.
9Useful Variations
Several variations extend the basic ideas. A double-ended queue, often called a deque, allows adding and removing at both ends, combining the flexibility of stacks and queues in one structure. It is handy for problems like sliding windows where you need access to both ends.
A priority queue removes items by importance rather than arrival order, always serving the highest-priority element first. It is typically built on a heap and is essential for scheduling and shortest-path algorithms. A circular queue reuses a fixed-size buffer efficiently by wrapping around, which is common in streaming and buffering scenarios.
These variations show how a simple core idea stretches to fit many needs. A deque generalizes both a stack and a queue at once. A priority queue relaxes the strict ordering in favor of importance. A circular queue optimizes for fixed memory. Learning the plain versions first gives you the foundation to understand each variation as a small, purposeful twist rather than a whole new concept.
10Implementing Them Yourself
Building a stack is a great first exercise. Wrap an array and expose push, pop, and peek, guarding against popping when empty. You will quickly appreciate how the restricted interface keeps the implementation tiny and bug-resistant compared to a general-purpose structure.
A queue is slightly more instructive because you must handle both ends efficiently. Try implementing one with a linked list, then try the elegant trick of using two stacks to simulate a queue, where one stack handles incoming items and the other handles outgoing ones. That exercise sharpens your understanding of how the two structures relate.
11Common Mistakes To Avoid
The most common bug is failing to check for an empty structure before popping or dequeuing, which causes errors when there is nothing to remove. Always guard these operations. Another pitfall is implementing a queue on a plain array and removing from the front by shifting all elements, which quietly turns a constant-time operation into a slow linear one.
Confusing the two structures is also common under pressure. When a problem needs the most recent item, you want a stack; when it needs the oldest, you want a queue. Slowing down to name the required order out loud helps you pick correctly and avoids subtle logic errors.
12Practice On SkillVeris
Stacks and queues are foundational, and the fastest way to make them second nature is to implement both and then use them to solve small problems. Try validating balanced parentheses with a stack, then simulate a task scheduler with a queue. These exercises turn abstract definitions into working intuition.
SkillVeris offers hands-on challenges that let you build stacks and queues and apply them to real algorithmic problems, with step-by-step visualizations of push, pop, enqueue, and dequeue. Work through them, implement the variations yourself, and these structures will become reliable tools you reach for automatically.
Get The Print Version
Download a PDF of this article for offline reading.
About the Publisher
SkillVeris Team
Engineering Team
Our engineering writers turn abstract code concepts into hands-on, project-driven learning experiences.
View all postsRelated Posts
Never miss an update
Get the latest tutorials and guides delivered to your inbox.
No spam. Unsubscribe anytime.