Skip to content
All apps

Stack and Queue

About this app

The same sequence of push and pop on a stack and in a queue: what comes out? The inside view shows what the construction costs: as a Python list every cell moves up one by one on pop(0), the counter reaches n(n−1)/2; the list with an index keeps everything; the linked list only rewires first, last and next. Ten examples from the slides with real Python runs, including undo, bracket checking, swapped lines with a self-loop and duck typing.

LIFO and FIFO

A stack returns the element put in last first: last in, first out. A queue returns the oldest element first: first in, first out. Both have the same interface of push and pop but behave differently. How expensive pop is depends on how the structure is built. A Python list removes at the end in constant time, but with pop(0) all remaining elements have to move up. A linked list with pointers to the first and last element needs only a few pointer changes at either end.

What the app shows

At the top the sequence of operations, the stack on the left and the queue on the right, and below each what pop returned. Four views show the inside of the queue: from outside; as a Python list with pop(0), where a counter tracks the shifts up to n(n−1)/2; as a list with a moving index that keeps everything; and as a linked list with first, last and next that only moves pointers. Nine further examples show a code board, a console and a memory diagram.

Try it yourself

Enter your own sequence of push and pop or pick one of the ten examples, including undo, bracket checking, swapped lines with a self-loop and duck typing. Before every pop the app can ask what will come out. Compare the inside views for longer sequences and watch the list's shift counter grow.

Frequently asked questions

What is the difference between a stack and a queue?
A stack works LIFO: the element inserted last comes out first, like a pile of plates. A queue works FIFO: the element inserted first comes out first, like a line at a checkout.
Why is list.pop(0) slow in Python?
A Python list stores its elements contiguously. Removing the first one makes all the others move up one position, which costs O(n). For queues, collections.deque inserts and removes at both ends in O(1).
What is a stack used for?
Wherever the most recent item is handled first: undo functions, checking matching brackets, the function call stack and depth-first search in graphs.
What does the Stack and queue app show?
A stack and a queue side by side with the same push and pop sequence, four inside views of the queue with counters for shifts and moved pointers, and ten Python examples with memory diagrams.

Subject: Computer science

More from Computer science

A VisuApp by heyprof: interactive, free in your browser, no sign-up. What is a VisuApp? · All apps