The big idea: A stack only lets you add and remove at one end — the top.
So the last item put in is the first one taken out. That is what LIFO means.
The same three items into a stack and a queue, then taken back out. Watch the orders diverge.
Interactive diagram
Explore the labelled diagram, charts and maps for this topic in full study mode.
Free preview
This is the free notes preview
You're reading the free notes. Aimnova Pro unlocks the full study experience — and you can try it with your first topic free to keep:
- FlashcardsLock in vocabulary and key terms with spaced repetition.
- Practice questionsAnswer exam-style questions and get instant AI marking.
- Mock exams & past-paper vaultSit full mocks and see exactly how examiners award marks.
- Personalised study planA daily plan built around your exam date and weak areas.
push and pop
- push(item) — put one on the top
- pop() — take the top one off, and return it
- Both touch only the top, so both are O(1)
- Nothing is shifted or searched for
peek and isEmpty
- peek() — look at the top without removing it
- isEmpty() — is there anything in it at all?
- Always check isEmpty before popping
- Popping an empty stack is an error
What you cannot do
- Reach the middle — the top is the only way in
- Search it without emptying it
- That restriction is the point, not a shortcoming
Why the restriction helps: Because every operation touches only the top, a stack is fast and predictable: no shifting, no searching, constant time however big it grows.
A structure that can do less can guarantee more.
Get feedback like a real examiner
Submit your answers and get instant feedback — what you did well, what's missing, and exactly what to write to score full marks.
Undo
The call stack
Checking brackets match
Going back
Stack overflow: A stack that keeps growing without anything being popped eventually runs out of memory.
The usual cause is a function that calls itself with no way to stop — which is where the phrase stack overflow comes from.
How this is tested — you must justify LIFO from the scenario, and trace pushes and pops correctly. It comes up two ways:
Paper 2 — working with code
- Explain a stack and its operations, 3-5 marks
- Trace a sequence of pushes and pops
- Say why a stack suits a described problem
Paper 2 — the algorithmic-thinking question
- Choose between a stack and a queue from behaviour alone
- Explain what would go wrong with the other one
The classic trap: Naming the structure without justifying it. The mark is for saying why the most recent item is the one wanted — undo, unwinding calls, matching brackets.
A text editor must support undo. Explain why a stack is the right structure, naming the operations used.
Model answer plan
See the mark-by-mark plan — for / against / judgement, with marking guidance — in study mode.