Courses / Computer Science XII (HSSC-II) – FBISE Complete SLO-Based Course
2.2 Data Structures: Lists, Arrays, Stacks and Queues
Unit 2 – Computational Thinking and Algorithms · 80 min read · 10 MCQs to check yourself
Stacks and queues – data structures and algorithms
1. What is a data structure?
A data structure is a way of organising and storing data so it can be used efficiently. Choosing the right one makes algorithms simpler and faster.
| Structure | Organisation | Access | Typical use |
|---|---|---|---|
| Array | Fixed size, same data type, stored side by side in memory | By index, O(1) | Marks of 40 students, pixels of an image |
| List (Python) | Ordered, grows and shrinks, can mix types | By index, O(1); insert in middle O(n) | Shopping cart, to-do list |
| Stack | LIFO – Last In, First Out | Only the top | Undo/redo, browser back button, function calls |
| Queue | FIFO – First In, First Out | Add at rear, remove at front | Printer jobs, ticket counter, CPU scheduling |
| Tree | Hierarchy – parent and children | From the root | Folders, org charts, BST (next lesson) |
| Dictionary | Key → value pairs | By key, O(1) average | Phone book, student records |
2. Arrays and lists
marks = [72, 85, 64] # a Python list
marks.append(90) # add at end
marks.insert(1, 58) # add at index 1
marks.remove(64) # remove a value
print(marks, len(marks), marks[0], marks[-1])
Output:
[72, 58, 85, 90] 4 72 90
3. Stack – LIFO
Think of a stack of plates: you put a plate on top (push) and take from the top (pop). Peek looks at the top without removing it.
stack = []
stack.append("type A") # push
stack.append("type B")
stack.append("delete B")
print("Top:", stack[-1]) # peek
print("Undo:", stack.pop()) # pop – last action undone first
print("Now:", stack)
Output:
Top: delete B
Undo: delete B
Now: ['type A', 'type B']
Undo/redo in a text editor uses two stacks: every action is pushed onto the undo stack; Undo pops it and pushes it onto the redo stack; Redo pops from the redo stack.
undo, redo = [], []
for action in ["write Hello", "bold", "write World"]:
undo.append(action)
redo.append(undo.pop()) # Undo
redo.append(undo.pop()) # Undo again
undo.append(redo.pop()) # Redo
print("undo:", undo)
print("redo:", redo)
Output:
undo: ['write Hello', 'bold']
redo: ['write World']
Stack overflow = pushing onto a full stack; stack underflow = popping from an empty stack.
4. Queue – FIFO
Like a line at a bank counter: people join at the rear (enqueue) and are served from the front (dequeue).
from collections import deque
printer = deque()
printer.append("CV.pdf") # enqueue
printer.append("Notes.docx")
printer.append("Photo.jpg")
print("Printing:", printer.popleft()) # dequeue – first come, first served
print("Waiting:", list(printer))
Output:
Printing: CV.pdf
Waiting: ['Notes.docx', 'Photo.jpg']
deque is used because removing from the front of a normal list is slow (O(n)); popleft() is O(1).
5. Choosing the right structure – situations
| Situation | Best structure | Why |
|---|---|---|
| Undo/redo in a word processor | Stack | Most recent action is undone first |
| Browser Back button | Stack | Last visited page comes back first |
| Students waiting for a fee counter | Queue | Fair – first come, first served |
| Print jobs from 30 computers | Queue | Jobs printed in order received |
Checking matching brackets ( [ ] ) |
Stack | The last opened bracket must close first |
| Company hierarchy | Tree | Parent–child levels |
| Roll number → student name | Dictionary | Fast lookup by key |
Short and long questions
1. Write a Python program to implement a queue of print jobs using enqueue and dequeue operations.
Model answer
from collections import deque
jobs = deque()
jobs.append("CV.pdf") # enqueue
jobs.append("Notes.docx")
jobs.append("Photo.jpg")
print("Printing:", jobs.popleft()) # dequeue → CV.pdf
print("Waiting:", list(jobs)) # ['Notes.docx', 'Photo.jpg']
2. A hospital wants software for (a) the order in which walk-in patients see a doctor, (b) the “undo last entry” feature for receptionists, and (c) storing departments and sub-departments. Recommend a data structure for each, justify your choice and show the main operations with a short Python example. (2 + 2 + 2)
Model answer
(a) Walk-in patients – Queue (FIFO). Fair: the first patient to arrive is seen first.
from collections import deque
patients = deque(); patients.append("Ali"); patients.append("Sana")
next_patient = patients.popleft() # Ali
(For emergencies a priority queue would serve the most serious case first.)
(b) Undo last entry – Stack (LIFO). The most recent entry must be undone first.
entries = []; entries.append("Ali – Room 2"); entries.append("Sana – Room 4")
entries.pop() # removes Sana – Room 4
(c) Departments – Tree. Hospital → Medicine, Surgery → Cardiology, Orthopaedics … has parent–child levels; a tree models the hierarchy and can be searched with DFS/BFS.
hospital = {"Hospital": ["Medicine", "Surgery"], "Medicine": ["Cardiology"], "Surgery": ["Orthopaedics"]}
3. Show the contents of a stack after each operation: push(5), push(8), pop(), push(3), push(9), pop(). What value is on top at the end?
Model answer
| Operation | Stack (bottom → top) |
|---|---|
| push(5) | 5 |
| push(8) | 5, 8 |
| pop() → 8 | 5 |
| push(3) | 5, 3 |
| push(9) | 5, 3, 9 |
| pop() → 9 | 5, 3 |
| Top at the end: 3. |
4. Define a data structure. Name any four data structures with one use of each.
Model answer
A data structure is a way of organising and storing data in memory so that it can be accessed and changed efficiently.
- List/array – marks of a class. Stack – undo/redo. Queue – printer jobs. Tree – folders/company hierarchy. (Dictionary – roll number → name.)
5. Explain how undo and redo work in a text editor using stacks.
Model answer
Two stacks are used. Each new action is pushed onto the undo stack (redo stack is cleared).
- Undo: pop the top action from the undo stack, reverse it, and push it onto the redo stack.
- Redo: pop from the redo stack, apply it again, and push it back onto the undo stack. Because both are LIFO, the most recent action is always undone/redone first.
6. Differentiate between a stack and a queue with one real-life example of each.
Model answer
| Stack | Queue |
|---|---|
| LIFO – last in, first out | FIFO – first in, first out |
| Insert (push) and remove (pop) at the same end – the top | Insert (enqueue) at the rear, remove (dequeue) from the front |
| Example: undo/redo, browser back button, pile of plates | Example: printer jobs, bank/ticket counter line |
This lesson ends with a quiz of 10 MCQs. Open the lesson on PrepOasis to take it and save your progress.
Previous: 2.1 Evaluating Computational Solutions: Efficiency, Clarity and Correctness · Next: 2.3 Trees: Binary Trees, BST, Traversals, DFS and BFS
All lessons in Computer Science XII (HSSC-II) – FBISE Complete SLO-Based Course