A Level Computer Science · Chapter 15 · Component 01: Computer systems
The way data is arranged decides what a program can do with it quickly, and four simple structures, arrays, records, stacks and queues, sit underneath almost every program.
This chapter teaches how arrays and records store data, and how stacks and queues control the order in which data is used. You will trace each structure by hand, calculate where items sit in memory, and choose the right structure for a job.
In this chapter · jump to a section
Start here
Your route through this chapter
By the end of this chapter you will be able to:
- use one-, two- and three-dimensional arrays, and calculate the position and address of an element
- define records and tuples, and explain when each is used
- trace push, pop and peek on a stack, including overflow and underflow
- explain how the call stack supports subroutines and recursion
- convert between infix and reverse Polish notation, and evaluate reverse Polish notation with a stack
- trace enqueue and dequeue on linear, circular and priority queues
- choose a suitable data structure for a problem, and justify the choice
Time: three sessions, about 4 hours, plus the programming task.
You need first: variables, loops and subroutines from Programming constructs, and binary storage sizes from Number systems and binary arithmetic.
The big picture
The big picture
Press Ctrl+Z in a word processor and your last change vanishes. Press it again and the change before that goes too. The program is keeping a pile of your changes, with the newest on top, and taking them off one at a time. That pile is a stack.
Send three documents to a shared printer and they come out in the order you sent them. The printer keeps a line of jobs, adding new ones at the back and printing from the front. That line is a queue.
These two structures are not about storing data so much as about order. A stack always gives back the most recent item first: last in, first out. A queue always gives back the oldest item first: first in, first out. Choosing between them is choosing which item a program deals with next.
Underneath both, and underneath almost every other structure, is the array. An array is a row of numbered boxes, all the same size, side by side in memory. Because they are side by side, the computer can jump straight to box 1,000 without looking at the 999 before it.
Arrays hold many values of one kind. Records hold several values of different kinds about one thing, such as a student's name, age and test score. Most real programs store arrays of records: a whole class of students, each one a record.
Stacks also run the computer itself. Every time a program calls a subroutine, the processor pushes a record of where to return onto the call stack. When the subroutine ends, that record is popped. Recursion, where a subroutine calls itself, would be impossible without it.
Queues, too, are everywhere in a computer. Keystrokes wait in a keyboard buffer, data packets wait in a router, and processes wait for their turn on the processor. A variation, the priority queue, lets urgent items jump ahead.
This chapter builds these structures from arrays, with pointers to mark their ends. You will see why a simple queue runs out of space, and how a circular queue fixes it with a single MOD operation.
One idea runs through the whole chapter. A data structure is a promise about which operations are cheap. An array promises fast access by position. A stack promises fast access to the newest item, and a queue to the oldest. A good programmer picks the structure whose promise matches the job.
Section 1
Arrays
One dimension
An array is a fixed-size collection of elements of the same data type, stored together and accessed by an index. In most languages, including the pseudocode in this course, the first element has index 0. An array of 10 elements has indices 0 to 9.
Because every element is the same size and they sit side by side, the computer can work out where any element is. Element i is at the start address plus i times the size of one element. That is why accessing any element takes the same time, O(1), however large the array.
Common mistake: counting array indices from 1. In zero-indexed arrays, the first element is at index 0 and the last of n elements is at index n − 1. Using index n reads past the end of the array, which crashes some programs and corrupts others.
Why access is fast, and inserting is slow
Reaching element 5,000 of an array takes one multiplication and one addition, exactly as for element 0. The computer never walks along the array to find it. That constant cost is the array's great strength, and it is why arrays sit underneath most other structures.
The price is paid when the contents change shape. To insert a value at the front of a full row of data, every other value must move one place along to make room. Deleting from the front means moving everything back. In the worst case that is n moves, so inserting or deleting in the middle is O(n).
Searching has a similar cost. An unsorted array must be checked element by element, which is a linear search. If the array is kept sorted, a binary search can halve the range at every step instead. Keeping it sorted, though, makes every insertion slower, because values must shift to keep their order.
Two dimensions
A two-dimensional array is a grid, with rows and columns. It suits data that is naturally a table, such as seats in a cinema, pixels in an image or marks for each student in each test. An element is written array[row][column].
Memory itself is a single line of addresses, so the grid must be laid out in a line. Most languages store it row by row, called row-major order: all of row 0, then all of row 1, and so on. Element [r][c] of a grid with C columns is then at position r × C + c.
Derivation: the address of an element in a 2D array
Before row r come rows 0 to r − 1. Each whole row holds C elements, so they fill r × C positions. Inside row r, columns 0 to c − 1 come first, which is c more.
Each element takes s bytes, and position 0 starts at the base address. So the element's first byte is the base plus s bytes for every element before it.
The same counting works in three dimensions. For an array declared [I][J][K], element [i][j][k] has i whole grids of J × K before it. Then come j whole rows of K, then k elements, giving position i × J × K + j × K + k.
Row-major order is not the only choice. Some languages, such as Fortran, store a grid column by column instead, called column-major order. The calculation then counts whole columns first. Exam questions say which order is used, so always read that detail before you start.
Worked example 1: finding an element in memory
A 2D array has 3 rows and 5 columns of 4-byte integers, starting at address 1000. Find the position and address of element [2][3].
| Working | Reason |
|---|---|
| Rows 0 and 1 come first: 2 × 5 = 10 elements | Row-major order stores whole rows in turn |
| Then 3 more elements along row 2: position 13 | Columns 0, 1 and 2 of row 2 come before it |
| Address = 1000 + 13 × 4 | Each element takes 4 bytes |
| Address 1052 | The element starts 52 bytes after the base |
Common mistake: swapping rows and columns. In array[row][column], the first index is the row. Calculating r × R + c with the number of rows R, instead of columns C, puts the element in the wrong place unless the grid is square.
Three dimensions
A three-dimensional array adds a third index, like a stack of grids. It might hold the temperature at each point of a 3D model, or the marks for each student in each test in each year. Element [i][j][k] is found the same way, by counting whole grids, then whole rows, then elements.
Worked example 2: the size of an array
A program stores a 10 by 20 grid of 4-byte integers. How much memory does the array need?
| Working | Reason |
|---|---|
| Elements: 10 × 20 = 200 | One element for every row and column |
| Each element takes 4 bytes | The size of one integer |
| Total: 200 × 4 = 800 bytes | Multiply the count by the size |
| The size is fixed when the array is created | A static array cannot grow later |
Choosing the order of loops
Because rows are stored one after another, a program that visits a 2D array row by row reads memory in order. Visiting column by column jumps a whole row's length at every step. Both give the same answers, but the row-by-row loop is usually faster, because the processor's cache fetches nearby addresses together.
Static and dynamic arrays
A static array has a fixed size, set when it is created. A dynamic array, such as a Python list, can grow. Behind the scenes it is still a static array; when it fills, the language creates a bigger one and copies everything across. That copy is slow, but it happens rarely, so adding an item is fast on average.
Arrays in Python
Python's built-in list behaves like a dynamic array. Its elements can even be of different types, because each cell really holds a reference to a value stored elsewhere. Exam pseudocode treats arrays more strictly: one data type, and a size fixed when the array is declared. A 2D array in Python is usually written as a list of lists, so grid[2][3] means row 2, then column 3.
Check yourself. A 2D array has 4 rows and 6 columns, stored row by row. What is the position of element [3][2]?
Show the answer
Three full rows of 6 come first, which is 18 elements. Then 2 more along row 3, so the position is 3 × 6 + 2 = 20.
Section 2
Records and tuples
Records
A record groups several related values, called fields, under one name. Each field has its own name and data type. A student record might hold a name as a string, an age as an integer and a score as a real. The fields are accessed by name, such as student.name.
record Student
name : string
age : integer
score : real
endrecord
pupil = new Student
pupil.name = "Asha"
pupil.age = 17
pupil.score = 82.5
Records keep related data together. Without them, a program would need separate arrays for names, ages and scores, kept carefully in step. One mistake in the index of one array, and a name would be paired with the wrong score.
Common mistake: confusing a record with an array. An array holds many values of the same type, reached by number. A record holds a fixed set of values of different types, reached by field name. A class list is an array of records, not a record of arrays.
Arrays of records
The two structures combine naturally. An array of records holds one record per item: class[0] is the first student, and class[0].score is that student's score. Looping over the array visits every student, and each field is reached by name.
Worked example 3: an array of records
A class of 30 students is stored as an array of Student records. Write an expression for the third student's score, and describe how to find the class average.
| Working | Reason |
|---|---|
| The third student is class[2] | Indices start at 0, so the third is index 2 |
| Their score is class[2].score | The field is reached by name, after a dot |
| Loop i from 0 to 29, adding class[i].score to a total | Visit every record in the array |
| Divide the total by 30 to get the average | The mean of the 30 scores |
Records in real languages
Python has no keyword called record. A class with only attributes plays the same part, and a dataclass writes most of that class for you. Other languages have a struct, which is a record by another name. In every case the fields are fixed when the structure is defined.
Records are also how data is stored in files. A file of fixed-length records gives every record the same number of bytes, so record n starts at byte n times the record length. That is the same calculation as finding an array element, and it lets a program jump straight to any record.
Tuples
A tuple is an ordered, fixed-length group of values that cannot be changed once it is made. It is like a lightweight record without field names. A coordinate (3, 7) or a colour (255, 128, 0) are natural tuples. In Python, tuples are written in round brackets.
Because a tuple is immutable, it is safe to share: no part of the program can change it by accident. Python uses this to let a function return several values at once, packed into a tuple.
Python also lets you unpack a tuple into separate variables in one line, as in x, y = point. Swapping two variables with a, b = b, a works the same way: the right-hand side builds a tuple, and the left-hand side unpacks it.
Choosing a structure
Use an array for many items of the same kind, especially when you need to reach them by position. Use a record for one item with several properties of different types. Use a tuple for a small fixed group of values that should not change.
Records and objects
A record holds data only. An object, which you meet in Object-oriented programming, bundles data with the methods that act on it. A record is therefore a good first step towards a class. If the only thing you need is a group of named fields, a record keeps the design simple.
Check yourself. Why is an array of records safer than three parallel arrays for storing students' names, ages and scores?
Show the answer
In an array of records, each student's name, age and score are kept together in one record. With parallel arrays, a mistake in one index or a sort of only one array would pair a name with the wrong age or score.
Section 3
Stacks
Last in, first out
A stack is a collection where items are added and removed at the same end, called the top. The last item added is the first removed: last in, first out, or LIFO. Think of a pile of plates. You add to the top and take from the top.
A stack has a small set of operations. Push adds an item to the top. Pop removes and returns the top item. Peek returns the top item without removing it. isEmpty and isFull test whether the stack can be popped or pushed.
Common mistake: thinking a stack removes the oldest item. A stack is last in, first out: pop always takes the most recent item. Removing the oldest item is what a queue does. Picture a pile of plates, not a line of people.
Implementing a stack with an array
A stack is usually built from an array and a pointer, called the top pointer, holding the index of the top item. An empty stack has top = −1. Push adds 1 to the pointer and stores the item there. Pop reads the item at the pointer and subtracts 1.
procedure push(item)
if top == maxSize - 1 then
print("stack overflow")
else
top = top + 1
stack[top] = item
endif
endprocedure
function pop()
if top == -1 then
print("stack underflow")
return null
else
item = stack[top]
top = top - 1
return item
endif
endfunction
Pushing onto a full stack is overflow; popping an empty stack is underflow. Both must be checked before the operation, or the program will write past the end of the array or read rubbish from below the start.
Every stack operation touches only the top cell and the top pointer. However many items the stack holds, push, pop and peek each take the same small number of steps. All three are O(1), which is why a stack is so cheap to use.
Notice that pop does not wipe the old value from the array. It only moves the pointer down. The old value is still in the cell, but it no longer counts as part of the stack, and the next push will overwrite it.
Common mistake: forgetting to check for underflow. Popping an empty stack reads from index −1, which is outside the array. Always test whether the stack is empty before popping, and decide what the program should do instead.
Static and dynamic stacks
A stack built on a fixed array is a static stack, and it can overflow. A dynamic stack grows as needed, for example by using a Python list with append and pop. A dynamic stack only fails when the whole computer runs out of memory. Exam questions usually describe a static stack, so they can ask about overflow.
Worked example 4: tracing a stack
A stack starts empty. Trace push A, push B, push C, pop, push D, pop, pop, giving the item each pop returns.
| Working | Reason |
|---|---|
| After three pushes the stack is A, B, C, with C on top | Each push adds to the top |
| Pop returns C, leaving A, B | The most recent item leaves first |
| Push D gives A, B, D; pop returns D | D is now the most recent item |
| Pop returns B, leaving A | B is now on top |
| Items popped: C, D, B | Last in, first out |
Worked example 5: overflow
A stack has room for 3 items. Trace push A, push B, push C, push D.
| Working | Reason |
|---|---|
| Push A, B and C: top moves from −1 to 0, 1, 2 | Each push adds one to the top pointer |
| The stack is now full, because top = 3 − 1 = 2 | The last index of a 3-item array is 2 |
| Push D: top would become 3, which is outside the array | Index 3 does not exist |
| The push is refused and overflow is reported | The check prevents writing past the end |
Stacks inside the processor
The processor keeps the address of the top of the call stack in a register called the stack pointer. Machine-code instructions push and pop values in a single step, adjusting the pointer as they go. In many processors the stack grows downwards, towards lower addresses, but the idea is exactly the same.
A stack's limited operations are a strength, not a weakness. Because the program can only reach the top item, it cannot disturb older items by mistake. Restricting access in this way makes programs easier to reason about and to test.
Check yourself. What does peek return for a stack holding A, B, C with C on top, and how does the stack change?
Show the answer
Peek returns C, the item on top. Unlike pop, it does not remove the item, so the stack still holds A, B and C afterwards.
Section 4
Uses of stacks
The call stack
When a program calls a subroutine, the processor must remember where to come back to. It pushes a stack frame onto the call stack, holding the return address, the parameters and the local variables. When the subroutine returns, its frame is popped and the program continues from the saved address.
If that subroutine calls another, a second frame goes on top. The most recently called subroutine is always the first to finish, which is exactly last in, first out. Recursion works the same way: each call of a recursive function gets its own frame.
Worked example 6: the call stack in recursion
A recursive function fact(n) returns 1 if n is 1, and otherwise n × fact(n − 1). Describe the call stack when fact(4) is called.
| Working | Reason |
|---|---|
| fact(4) pushes a frame, then calls fact(3), which pushes another | Each call adds a frame on top |
| fact(2) and fact(1) push frames too: the stack is 4 frames deep | The deepest call is on top |
| fact(1) returns 1 and its frame is popped | The base case finishes first |
| Frames pop in turn, returning 2, 6, then 24 | Each call finishes after the one it made |
Each frame uses memory. A recursion thousands of calls deep may fill the space set aside for the stack. That is a stack overflow, and the program crashes.
The same thing explains why an iterative version of an algorithm can be safer than a recursive one. A loop reuses the same variables on every pass, so its memory use does not grow. A recursive version needs a new frame for every call that has not yet returned.
Undo and backtracking
Undo keeps each change on a stack, so the most recent can be reversed first. Back buttons in web browsers do the same with pages visited. Backtracking algorithms, such as depth-first search, push choices so that they can return to the last decision point when a path fails.
Reverse Polish notation
We usually write arithmetic in infix notation, with operators between their operands, as in 3 + 4. Reverse Polish notation, or RPN, puts each operator after its operands: 3 4 +. RPN needs no brackets and no precedence rules, so it is very easy for a computer to evaluate.
To evaluate RPN, read the tokens from left to right. Push every number onto a stack. When you meet an operator, pop two numbers, apply the operator, and push the result. At the end, the single value on the stack is the answer.
Worked example 7: evaluating RPN
Evaluate the reverse Polish expression 3 4 + 2 * 5 −.
| Working | Reason |
|---|---|
| Push 3 and 4; + pops 4 and 3 and pushes 7 | An operator works on the top two values |
| Push 2; * pops 2 and 7 and pushes 14 | Multiply the top two values: 7 × 2 = 14 |
| Push 5; − pops 5 and 14 and pushes 9 | The second value popped is the left operand: 14 − 5 |
| Result: 9 | The single value left on the stack |
Common mistake: popping the operands in the wrong order. The first value popped is the right-hand operand and the second is the left. For 8 2 −, the answer is 8 − 2 = 6, not 2 − 8. Order matters for subtraction, division and powers.
Converting infix to RPN
To convert by hand, write the operands in the same order, and place each operator after the two things it combines. Brackets are done first, then multiplication and division, then addition and subtraction. So A + B × C becomes A B C × +, because B × C is done first.
A computer converts with a stack too, using a method called the shunting-yard algorithm. Operands go straight to the output. Operators wait on a stack, and an operator is moved to the output when a new operator of equal or lower priority arrives. A left bracket waits on the stack until its matching right bracket arrives.
When the expression ends, any operators still waiting are popped to the output. The stack holds operators back until everything they apply to has been written. That is why the operators come out after their operands.
Compilers and calculators use exactly this pair of steps. The expression is converted to reverse Polish notation once, then evaluated with a stack every time it is needed. Some processors work directly on a stack of values, so reverse Polish notation maps almost straight onto their instructions.
Worked example 8: converting to RPN
Convert (3 + 4) × 2 − 5 to reverse Polish notation.
| Working | Reason |
|---|---|
| The bracket is done first: 3 + 4 becomes 3 4 + | Brackets have the highest priority |
| Multiply that by 2: 3 4 + 2 × | The × follows both of its operands |
| Subtract 5: 3 4 + 2 × 5 − | The − is done last, so it comes last |
| Check by evaluating: the result is 9, as before | Both forms give the same value, since (3 + 4) × 2 − 5 = 9 |
Why reverse Polish notation needs no brackets
In infix, A + B × C and (A + B) × C mean different things, and only brackets or precedence rules tell them apart. In reverse Polish notation the two become A B C × + and A B + C ×. The order of the tokens alone fixes which operation happens first, so there is never any doubt.
That also makes evaluation a single left-to-right pass. The program never needs to look ahead or go back, and the stack is never deeper than the number of operands waiting. This is why early pocket calculators and some programming languages, such as PostScript, were built around it.
Check yourself. Evaluate the reverse Polish expression 8 2 − 3 / and say what the wrong operand order would give.
Show the answer
Push 8 and 2; − gives 8 − 2 = 6. Push 3; / gives 6 ÷ 3 = 2. Taking the operands the wrong way round gives 2 − 8 = −6, then 3 ÷ −6 = −0.5.
Section 5
Queues
First in, first out
A queue is a collection where items join at one end, the rear, and leave from the other, the front. The first item added is the first removed: first in, first out, or FIFO. It works like a line of people at a till.
Its operations are enqueue and dequeue. Enqueue adds an item at the rear, and dequeue removes and returns the item at the front. isEmpty and isFull test whether the queue can be dequeued or enqueued.
Figure 15.1 compares a stack and a queue fed with the same items. Step through and compare what each gives back. Then switch on the wrong model, which treats the stack as if it were a queue.
Stack against queue
- Contents
- A, B
- Removed so far
- C
- Rule
- last in, first out
A linear queue
A simple linear queue uses an array with two pointers. The front pointer marks the next item to leave and the rear pointer marks the last item to join. Enqueue adds 1 to rear and stores the item. Dequeue reads the item at front and adds 1 to front.
Both pointers only ever move forwards. When rear reaches the end of the array, no more items can be added, even if items have left from the front. The cells they freed cannot be reused.
The queue is empty when front has moved past rear, and it reports full when rear is at the last cell. Many programs also keep a count of items, which makes both tests simpler. Dequeue does not need to wipe the cell, because the front pointer alone decides which cells count.
Queues appear wherever one part of a system produces work faster or slower than another part uses it. A keyboard buffer holds keystrokes until the program reads them. A print server holds jobs until the printer is free. Breadth-first search holds the nodes it has found but not yet visited.
Common mistake: thinking a linear queue reuses freed space. In a linear queue, front and rear only move towards the end of the array. Once rear reaches the last cell, the queue reports full, even if dequeued cells at the start are empty. A circular queue fixes this.
Worked example 9: a linear queue fills up
A linear queue has 4 cells. Trace enqueue A, B, C, then dequeue twice, then enqueue D, E and F.
| Working | Reason |
|---|---|
| Enqueue A, B, C: they fill cells 0, 1 and 2 | The rear pointer moves to 2 |
| Dequeue twice removes A and B: front moves to 2 | Cells 0 and 1 are now empty |
| Enqueue D fills cell 3, the last cell | The rear pointer moves to 3 |
| Enqueue E and F are refused as full, though cells 0 and 1 are free | rear cannot move past the end |
Shuffling instead
One fix is to move every item forward after each dequeue, so the front is always cell 0. That works, but it makes every dequeue O(n), because all the remaining items must be copied. For a busy queue, that is far too slow.
Derivation: the cost of shuffling a queue
Suppose a queue holds n items and they are dequeued one by one, shuffling after each. When k items remain, removing the front one means moving the other k − 1 forward. Add the moves for k = n down to k = 1.
Spread over the n dequeues, the average cost of one dequeue is the total divided by n.
The average grows in step with n, so each dequeue is O(n). For a queue of 1,000 items that is about 500 moves per dequeue, where a circular queue needs none.
Queues in simulations
Programs that model the real world often use queues. A model of a supermarket might enqueue each arriving customer and dequeue one whenever a till becomes free. Counting how long items wait in the queue tells the shop how many tills to open. The same idea is used to design road junctions, call centres and network routers.
Check yourself. In a linear queue of 6 cells, front is 4 and rear is 5. How many items does it hold, and can another be enqueued?
Show the answer
It holds 2 items, in cells 4 and 5. Another cannot be enqueued, because rear is already at the last cell, even though cells 0 to 3 are free.
Section 6
Circular and priority queues
The circular queue
A circular queue treats the array as a ring. When a pointer reaches the last cell, its next move takes it back to cell 0. This is done with the MOD operator: the next position after i is (i + 1) MOD n, for an array of n cells.
The queue also keeps a count of its items, or compares the pointers, to tell whether it is full or empty. It is full when the count equals n, and empty when the count is 0. Every enqueue and dequeue is now O(1), and no space is wasted.
The count matters more than it might seem. In a full circular queue, rear sits just behind front. In an empty one, after the last item leaves, rear also sits just behind front. The pointers alone cannot tell these two cases apart, so the count, or one deliberately unused cell, settles it.
procedure enqueue(item)
if size == maxSize then
print("queue full")
else
rear = (rear + 1) MOD maxSize
queue[rear] = item
size = size + 1
endif
endprocedure
Common mistake: moving the rear pointer without MOD. Writing rear = rear + 1 in a circular queue runs the pointer off the end of the array. The wrap-around needs (rear + 1) MOD maxSize, which sends the pointer from the last cell back to cell 0.
Figure 15.2 runs the same operations on a linear and a circular queue. Step through both and see where the linear queue refuses items that the circular queue accepts. Then switch on the wrong model, which forgets the MOD.
Linear and circular queues
- Items in the queue
- 2
- Dequeued so far
- A, B
- Refused as full
- none
Worked example 10: a circular queue wraps round
A circular queue has 4 cells. Trace enqueue A, B, C, dequeue twice, then enqueue D, E and F.
| Working | Reason |
|---|---|
| Enqueue A, B, C into cells 0, 1, 2; dequeue A and B | front moves to 2, as before |
| Enqueue D into cell 3; rear = (2 + 1) MOD 4 = 3 | Still inside the array |
| Enqueue E: rear = (3 + 1) MOD 4 = 0, so E goes in cell 0 | The pointer wraps to the start |
| Enqueue F into cell 1: the queue holds C, D, E, F, with front 2 and rear 1 | Every cell is reused, and the queue is full |
Priority queues
In a priority queue, each item has a priority. The item with the highest priority leaves first, whatever its arrival time. Items with equal priority leave in the order they arrived. An operating system uses one to run urgent processes ahead of background tasks.
Common mistake: serving a priority queue in arrival order. A priority queue is not first in, first out overall. An urgent item that arrives last still leaves first. Arrival order only decides between items of equal priority.
A priority queue can be built in several ways. One is to keep the items in order of priority, so that each new item is inserted in the right place. Dequeue is then O(1), but enqueue is O(n), because later items must shift along to make room.
Another way keeps a separate ordinary queue for each priority level. Dequeue checks the most urgent queue first and moves on only if it is empty. That works well when there are only a few levels, as there are in an operating system's scheduler.
Worked example 11: a priority queue
Jobs arrive in the order print (priority 3), alarm (1), email (2), backup (3) and key (1), where 1 is most urgent. Give the order they are served.
| Working | Reason |
|---|---|
| Priority 1: alarm, then key, in arrival order | Most urgent first; ties keep arrival order |
| Priority 2: email | It is the next most urgent |
| Priority 3: print, then backup | Least urgent, in arrival order |
| Order: alarm, key, email, print, backup | Priority first, then arrival |
Choosing a structure
Use a stack when the most recent item must be handled first: undo, the call stack, backtracking, evaluating RPN. Use a queue when items must be handled in arrival order: printing, buffers, breadth-first search. Use a priority queue when some items must jump ahead.
Many real systems combine these structures. A web browser keeps a stack of pages for its back button and a queue of downloads. An operating system keeps a priority queue of processes and a stack for every running program. Recognising which order each part needs is most of the design work.
Check yourself. A circular queue has 5 cells and rear is 4. Where does the next item go, and why?
Show the answer
It goes in cell 0, because the new rear is (4 + 1) MOD 5 = 0. The MOD wraps the pointer from the last cell back to the start of the array.
Reference
Key algorithms and definitions
| Term or algorithm | What it means | Example | Cost or rule to learn |
|---|---|---|---|
| Array | Fixed-size, same type, reached by index | scores[0] is the first | Access is O(1); indices from 0 |
| Row-major order | 2D array stored row by row | [2][3] of 5 columns is position 13 | Position = row × columns + column |
| Record | Named fields of different types | student.score | Keeps related data together |
| Tuple | Fixed, ordered, unchangeable group | (3, 7) | Cannot be changed once made |
| Stack | Last in, first out | Undo, call stack | push, pop, peek; check overflow and underflow |
| Reverse Polish notation | Operators after their operands | 3 4 + 2 × | Evaluate with a stack; second pop is the left operand |
| Linear queue | First in, first out, pointers only move forwards | Wastes freed cells | enqueue at rear, dequeue at front |
| Circular queue | Pointers wrap round the array | rear = (rear + 1) MOD n | Reuses space; O(1) operations |
| Priority queue | Highest priority leaves first | Urgent processes | Ties keep arrival order |
Programming task
Programming task: a stack calculator
Aim
Write a Python program that evaluates reverse Polish notation with an array-based stack. The stack must report overflow and underflow, and the program must reject an invalid expression rather than give a wrong answer.
Design
A class Stack holds a fixed-size list, a top pointer starting at −1, and methods push, pop and is_empty. The evaluate function splits the expression into tokens. Numbers are pushed. Each operator pops the right operand, then the left, and pushes the result.
At the end, exactly one value should remain. If an operator finds fewer than two values, or more than one value is left, the expression is invalid. These checks catch malformed input before it produces a misleading result.
Code
class Stack:
def __init__(self, size):
self.items = [None] * size
self.top = -1
def push(self, item):
if self.top == len(self.items) - 1:
raise OverflowError("stack overflow")
self.top += 1
self.items[self.top] = item
def pop(self):
if self.top == -1:
raise IndexError("stack underflow")
item = self.items[self.top]
self.top -= 1
return item
def evaluate(expression, size=10):
stack = Stack(size)
for token in expression.split():
if token in "+-*/":
right = stack.pop()
left = stack.pop()
if token == "+": stack.push(left + right)
elif token == "-": stack.push(left - right)
elif token == "*": stack.push(left * right)
else: stack.push(left / right)
else:
stack.push(float(token))
result = stack.pop()
if stack.top != -1:
raise ValueError("too many values")
return result
print(evaluate("3 4 + 2 * 5 -"))
Popping the right operand first matters for − and /. The final check that the stack is empty after taking the result catches an expression with too few operators.
Testing
| Test | Input | Expected output | Why this test |
|---|---|---|---|
| 1 | "3 4 + 2 * 5 -" | 9.0 | Matches worked example 7 |
| 2 | "8 2 - 3 /" | 2.0 | Operand order for − and / |
| 3 | "5" | 5.0 | A single number is valid |
| 4 | "3 +" | stack underflow | An operator with too few operands |
| 5 | "3 4" | too many values | Too few operators |
| 6 | "1 2 3 4" with size 3 | stack overflow | More numbers than the stack can hold |
| 7 | "2 3 4 * +" | 14.0 | Multiplication before addition, from A B C × + |
Evaluation
The program gives the right answer for every valid expression and refuses every invalid one with a clear error. Tests 4 to 6 show that the checks for underflow, overflow and leftover values all work.
An improvement would add an infix-to-RPN converter, so users can type ordinary expressions. Another would support the power operator, which is right-associative and needs care in conversion.
Practice
Practice ladder
Rung 1: Recall and fluency
Q1. State what LIFO and FIFO stand for, and name the structure that each describes.
Worked solution to Q1
LIFO is last in, first out, which describes a stack. FIFO is first in, first out, which describes a queue.
Q2. List the operations of a stack and say what each does.
Worked solution to Q2
Push adds an item to the top. Pop removes and returns the top item. Peek returns the top item without removing it. isEmpty and isFull test whether the stack can be popped or pushed.
Q3. Define a record, and give one difference between a record and an array.
Worked solution to Q3
A record is a group of named fields that can have different data types, such as a name and an age. An array holds many elements of the same type, reached by an index rather than by name.
Rung 2: Application
Q4. A 2D array has 6 rows and 8 columns of 4-byte integers, starting at address 2000. Find the address of element [3][5].
Worked solution to Q4
Three full rows of 8 come first, and then 5 more, so the position is 3 × 8 + 5 = 29. Each element takes 4 bytes, so the address is 2000 + 29 × 4 = 2116.
Q5. Find the value of the reverse Polish expression 6 2 + 5 3 − ×, showing the stack.
Worked solution to Q5
Push 6 and 2, then + pops both and pushes 8. Push 5 and 3, then − pops both and pushes 5 − 3 = 2, so the stack holds 8 and 2. Then × pops 2 and 8 and pushes 8 × 2 = 16. The result is 16.
Q6. Convert (A + B) × (C − D) to reverse Polish notation.
Worked solution to Q6
Each bracket becomes its own group: A B + and C D −. The × combines the two groups, so it comes last. The result is A B + C D − ×.
Q7. A stack starts empty. Trace push 5, push 9, pop, push 2, push 7, pop, pop, and give the values popped.
Worked solution to Q7
After push 5 and push 9, pop returns 9, leaving 5. Push 2 and push 7 give 5, 2, 7. Pop returns 7, then pop returns 2, leaving 5. The values popped are 9, 7 and 2.
Rung 3: Analysis
Q8. Trace a circular queue of 5 cells through the operations enqueue A, B, C, D, dequeue twice, enqueue E and F, dequeue, then enqueue G. Give the final front and rear.
Worked solution to Q8
A to D fill cells 0 to 3, and two dequeues move front to 2. E goes in cell 4 and F wraps to cell 0. One more dequeue removes C, moving front to 3. G goes in cell 1. So front is 3 and rear is 1, with the queue holding D, E, F and G.
Q9. Explain why a linear queue of 5 cells can refuse an item even when it holds only 2 items.
Worked solution to Q9
In a linear queue the pointers only move forwards. If rear has reached the last cell, the queue reports full, even though dequeued items have freed cells at the start. Those cells cannot be reused without moving every item.
Q10. Suppose a recursive function calls itself 2,000 times before reaching its base case, and each stack frame uses 64 bytes. Estimate the stack space used, and explain the risk.
Worked solution to Q10
At its deepest, 2,000 frames are on the stack at once, using 2,000 × 64 = 128,000 bytes. If the space set aside for the stack is smaller, pushing another frame causes a stack overflow and the program crashes.
Q11. Jobs arrive as scan (2), print (1), save (2), alert (1), where 1 is most urgent. Give the order a priority queue serves them.
Worked solution to Q11
The priority 1 jobs go first, in arrival order: print, then alert. The priority 2 jobs follow, in arrival order: scan, then save. The order is print, alert, scan, save.
Rung 4: Stretch
Q12. Show that, for a circular queue of n cells, (i + 1) MOD n gives the next cell for every i from 0 to n − 1.
Worked solution to Q12
For i from 0 to n − 2, i + 1 is less than n, so MOD leaves it unchanged and the pointer moves on by one. For i = n − 1, i + 1 = n, and n MOD n = 0, so the pointer wraps back to the start of the array.
Q13. Explain how two stacks could be used to make a queue, and why it gives first in, first out order.
Worked solution to Q13
Push new items onto stack 1. To dequeue, if stack 2 is empty, pop everything from stack 1 and push it onto stack 2, which reverses the order. Then pop from stack 2. Reversing twice restores the arrival order, so the oldest item leaves first.
Q14. A 3D array is declared as grid[4][5][6], stored with the last index changing fastest. Find the position of grid[1][2][3].
Worked solution to Q14
One whole layer of 5 × 6 = 30 elements comes before layer 1. Within it, two whole rows of 6 come first, which is 12 more. Then 3 more elements, so the position is 30 + 12 + 3 = 45.
Exam practice
Exam technique and worked answer workshop
Trace questions on stacks and queues reward clear layouts. Draw the array with its index numbers, and update the pointers after every operation. State the value returned by each pop or dequeue, and say clearly when an operation is refused for overflow, underflow or a full queue.
For address calculations, write the formula before the numbers: position = row × columns + column, then address = base + position × size. A wrong final answer with a correct formula still earns method marks.
When choosing a structure, link it to the order the problem needs. "Undo must reverse the most recent change first, so a stack is needed" is far stronger than "use a stack". Mention the operations you would use.
Exam question 1 (4 marks · Paper 02 · about 5 minutes)
A stack is initially empty. The operations push 4, push 7, push 1, pop, push 6, pop, pop are carried out.
(a) State the values returned by the three pops, in order. [3]
(b) State the contents of the stack at the end. [1]
Mark scheme for exam question 1
- B1 first pop returns 1
- B1 second pop returns 6
- B1 third pop returns 7
- B1 the stack holds only 4
Exam question 2 (5 marks · Paper 02 · about 6 minutes)
A 2D array marks has 6 rows and 8 columns of 4-byte integers. It is stored in row-major order starting at address 2000.
(a) Calculate the address of marks[3][5]. [3]
(b) Calculate the total memory the array uses. [2]
Mark scheme for exam question 2
- M1 position = 3 × 8 + 5
- A1 position 29
- A1 address 2000 + 29 × 4 = 2116
- M1 6 × 8 = 48 elements
- A1 48 × 4 = 192 bytes
Exam question 3 (5 marks · Paper 02 · about 7 minutes)
(a) Convert the infix expression (A + B) × (C − D) to reverse Polish notation. [2]
(b) Show how a stack is used to evaluate 6 2 + 5 3 − ×, giving the final result. [3]
Mark scheme for exam question 3
- M1 each bracket converted: A B + and C D −
- A1 A B + C D − ×
- M1 numbers pushed, and each operator pops two values and pushes the result
- M1 intermediate results 8 and 2 on the stack
- A1 16
Exam question 4 (5 marks · Paper 02 · about 7 minutes)
A circular queue is stored in an array of 5 cells, numbered 0 to 4. It starts empty with front = 0.
(a) Give the contents of the array and the front and rear pointers after: enqueue A, B, C, D, dequeue, dequeue, enqueue E, enqueue F. [3]
(b) Explain how the MOD operator lets the queue reuse cells. [2]
Mark scheme for exam question 4
- B1 cells hold F, empty, C, D, E: F in cell 0 and C, D, E in cells 2 to 4
- B1 front = 2
- B1 rear = 0
- B1 the next position is calculated as (rear + 1) MOD 5
- B1 after cell 4 this gives 0, so the pointer wraps to the start and reuses freed cells
Exam question 5 (6 marks · Paper 02 · about 9 minutes)
A school's printing system and its document editor are being designed. Discuss which data structures should be used for the print jobs, for urgent jobs from staff, and for the editor's undo feature.
Mark scheme for exam question 5
Level 3 (5–6 marks): a clear choice of structure for all three needs, each justified by the order in which items must be handled. How each structure works, such as wrapping a circular queue or checking for overflow, is discussed. The answer is well organised and uses technical terms accurately.
Level 2 (3–4 marks): correct structures for at least two needs, with some justification. There is little on how the structures work.
Level 1 (1–2 marks): some relevant points, such as naming a queue for printing, with little justification. The answer may lack structure.
0 marks: no response or no response worthy of credit.
Indicative content:
- print jobs should be printed in the order they were sent, so a queue, first in, first out
- a circular queue reuses space, so the print server never wastes freed cells
- urgent staff jobs must jump ahead, so a priority queue is needed
- jobs of equal priority are printed in arrival order
- undo must reverse the most recent change first, so a stack, last in, first out
- each edit is pushed; undo pops the top edit and reverses it
- the undo stack has a limited size, so the oldest edits may be discarded when it is full
- empty and full checks prevent underflow and overflow in every structure
Annotated model answer: exam question 5
"Print jobs must come out in the order they were sent, so they should be held in a queue, which is first in, first out. A circular queue is best, because its pointers wrap round with MOD, so cells freed by printed jobs are reused." (Queue, justified, with a detail.)
"Urgent jobs from staff must be printed before waiting student jobs. A priority queue does this: the highest-priority job leaves first, and jobs with the same priority leave in arrival order." (Priority queue, justified.)
"Undo must reverse the most recent change first, then the one before it. That is last in, first out, so a stack is needed. Each edit is pushed as it happens, and undo pops the top edit and reverses it." (Stack, justified, with its operations.)
"Each structure has a fixed size, so the system must check for a full queue or stack before adding, and for an empty one before removing. For undo, the oldest edits can be dropped when the stack is full." (Overflow and underflow.)
This answer reaches Level 3 and scores 6 marks. Each choice is tied to the order the task needs, and the implementation is considered.
Exam question 6 (6 marks · Paper 02 · about 9 minutes)
A stack is stored in an array called stack of size maxSize, with an integer top that is −1 when the stack is empty. Write a procedure push(item) and a function pop() that check for overflow and underflow.
Mark scheme for exam question 6
- B1 push checks whether top == maxSize − 1 and reports overflow
- B1 otherwise push adds 1 to top
- B1 then stores item at stack[top]
- B1 pop checks whether top == −1 and reports underflow
- M1 otherwise pop reads the item at stack[top]
- A1 then subtracts 1 from top and returns the item
Annotated model answer: exam question 6
procedure push(item)
if top == maxSize - 1 then
print("Stack overflow")
else
top = top + 1
stack[top] = item
endif
endprocedure
function pop()
if top == -1 then
print("Stack underflow")
return null
endif
item = stack[top]
top = top - 1
return item
endfunction
The overflow check comes before the pointer moves, which earns the first mark. Incrementing top before storing earns the next two, because the item must go in the new top cell. The underflow check, reading the top item, then decrementing the pointer earn the last three. Reading before decrementing matters: the other way round would return the wrong item.
Exam question 7 (4 marks · Paper 01 · about 5 minutes)
(a) Explain how a stack is used when one subroutine calls another. [2]
(b) Explain why a recursive function with no base case causes a program to crash. [2]
Mark scheme for exam question 7
- B1 a stack frame holding the return address, parameters and local variables is pushed when a subroutine is called
- B1 when the subroutine ends, its frame is popped and execution returns to the saved address
- B1 without a base case, the function keeps calling itself, pushing a new frame each time
- B1 the call stack eventually runs out of space, causing a stack overflow
Exam question 8 (5 marks · Paper 02 · about 7 minutes)
A library stores details of each book: its title, its author, the year it was published and whether it is on loan.
(a) Define a record structure called Book with suitable field names and data types. [3]
(b) The books are stored in an array of Book records called shelf. Write an expression for the title of the fifth book. [1]
(c) Give one reason for using an array of records rather than four separate arrays. [1]
Mark scheme for exam question 8
- B1 title and author as strings
- B1 year as an integer
- B1 onLoan as a Boolean, inside a record definition
- B1 shelf[4].title
- B1 all the details of one book are kept together, so they cannot get out of step
Connections
Synoptic link
These structures are the foundations for others. Linked lists, hash tables, graphs and trees builds dynamic structures from nodes and pointers, often stored in arrays like those here. Graph traversal and shortest paths uses a queue for breadth-first search and a stack for depth-first search.
The call stack links to Subroutines and recursion, which explains how each call gets its own frame. In Processor architecture and performance, the stack pointer is a register, and pushing and popping are single machine instructions.
Synoptic question 1. A circular queue in a keyboard buffer holds 16 keystrokes. Keys arrive at 10 a second, and the program reads them at 8 a second. How many seconds until the buffer is full, starting empty?
Answer to synoptic question 1
The queue gains 10 − 8 = 2 keystrokes each second. It holds 16, so it fills after 16 ÷ 2 = 8 seconds. After that, new keystrokes are lost unless the program reads faster.
Recap
Recap and next step
- An array holds elements of one type, reached by an index from 0; a 2D element [r][c] is at position r × columns + c in row-major order.
- A record groups named fields of different types; a tuple is a fixed, unchangeable group of values.
- A stack is last in, first out, with push, pop and peek; check for overflow before pushing and underflow before popping.
- The call stack holds a frame for each active subroutine; reverse Polish notation is evaluated with a stack, the second value popped being the left operand.
- A queue is first in, first out; in a linear queue the pointers only move forwards, wasting freed cells.
- A circular queue wraps its pointers with MOD to reuse space; a priority queue serves the most urgent item first.
Next chapter: Linked lists, hash tables, graphs and trees builds structures that grow and shrink, using nodes joined by pointers.
For your exam board
OCR A Level Computer Science (H446): this chapter covers arrays, records, tuples, stacks and queues in section 1.4.2, Data structures, in Component 01, Computer systems, and the algorithms for them in section 2.3.1, Algorithms, in Component 02. Reverse Polish notation is in section 1.4.3, alongside Boolean algebra.
AQA A Level Computer Science (7517): arrays, records, stacks, queues, including circular and priority queues, and the use of a stack for subroutine calls appear in the fundamentals of data structures section, assessed on Paper 1. Reverse Polish notation is in the fundamentals of algorithms section.