Data structures and algorithms · Lesson 17 of 60 · Code lesson, JavaScript or Python · Optional
Stacks and queues
A stack is last in, first out, like a pile of plates where you take from the top.
A queue is first in, first out, like a line at a shop where you serve the front.
Both are lists with a rule about which end you add to and which end you take from.
Worked example
In JavaScript, push adds to the end, pop removes from the end, and shift removes from the front.
const stack = [];
stack.push("a");
stack.push("b");
console.log(stack.pop());Output: b
In Python, append adds to the end, pop() removes from the end, and pop(0) removes from the front.
stack = []
stack.append("a")
stack.append("b")
print(stack.pop())Output: b
Your turn
The program takes words from the front, like a queue, so they print in the same order. Change it to take from the end, like a stack, so the words print in reverse.
Your program is checked with these 3 inputs:
Input:
a b c
Expected output:
c b a
Input:
one two
Expected output:
two one
Input:
x
Expected output:
x
Loading your practice…
Preparing your workspace…