Recursion, Stacks, Queues and Linked Lists

IB Computer Science · Abstract Data Structures (HL)

Recursion. A recursive sub-program calls itself on a smaller version of the same problem. Every correct recursion needs two parts: a base case that returns without recursing, and a recursive case that moves strictly towards the base case. Omitting either produces infinite recursion. Recursion is implemented using the call stack: each call places a new frame holding its parameters, local variables and return address, and the frames are removed in reverse order as the calls return. This is why very deep recursion causes a stack overflow, and why an equivalent iterative solution generally uses less memory. Recursion is chosen when the problem itself is defined recursively — tree traversal, divide and conquer, backtracking — because the code then mirrors the definition.

Static and dynamic structures. A static structure such as an array has its size fixed when it is created: memory is allocated once, elements are contiguous, and any element can be reached directly from its index. A dynamic structure such as a linked list grows and shrinks at run time, with each node allocated as needed. The trade-off is fundamental: arrays give constant-time access by index but cannot grow and waste space if over-allocated; linked lists grow freely and allow insertion in constant time once the position is known, but require extra memory for pointers and can only be reached by following the chain from the start.

Stacks. A stack adds and removes at the same end, so it is last in, first out. Its operations are push, pop, isEmpty and often peek. It is the correct structure whenever a program must return to where it just came from: the call stack itself, undo functionality, checking balanced brackets, evaluating expressions in reverse Polish notation, and backtracking through a maze.

Queues. A queue adds at one end and removes at the other, so it is first in, first out. Its operations are enqueue, dequeue, isEmpty. It is the correct structure whenever items must be served in the order they arrived: print spooling, process scheduling, buffering between a fast producer and a slow consumer, and breadth-first traversal. A circular queue lets the pointers wrap around to the start of the array so that positions freed at the front can be reused, which prevents the queue reporting itself full while space remains.

Linked lists. Each node holds data and a pointer to the next node; the last pointer is null. A doubly linked list also points backwards, allowing traversal in both directions at the cost of an extra pointer per node. A circular linked list has the last node point back to the first.

THE SAME INPUT SEQUENCE A B C D — TWO DIFFERENT OUTPUT ORDERS STACK — LAST IN, FIRST OUT A (bottom) B C D (top) push và pop SAME end Output order: D C B A REVERSES the input sequence QUEUE — FIRST IN, FIRST OUT A B C D FRONT REAR dequeue enqueue Output order: A B C D KEEPS the input sequence — add at one end, remove from the OTHER end A CIRCULAR queue reuses cells that have been vacated at the front, avoiding the queue being "full" while the array still has room STACK is used when you need to GO BACK function calls · undo · backtracking · expressions QUEUE is used when you need FAIRNESS in order of arrival print queue · process scheduling · data buffer · level-order traversal
The two structures differ in exactly one respect, and remembering that one point is enough to answer every related question: a STACK adds and removes at the SAME end, while a QUEUE adds at one end and removes from the OTHER end. Every other property can be derived from that. Why a stack reverses the order. The element that went in last sits at the top, so it is the first to be removed. This is exactly why a stack is the right structure for every problem that needs to return to the place just left: the call stack remembers where to return after each function call; the undo feature gives back the most recent action first; a backtracking algorithm returns to the nearest fork; and checking that brackets are balanced needs to match the nearest opening bracket. Why a queue preserves the order. The element that went in first sits at the front and is removed first, so a queue is the right structure for every problem that needs fair treatment in order of arrival: the print queue, the waiting queue of a process scheduler, a buffer between a fast producer and a slow consumer, and level-by-level graph traversal. The circular queue is a detail often asked about separately. If a queue is implemented with a straight array, after many removals both the front pointer and the rear pointer move toward the end of the array, and at some point the queue reports "full" while the start of the array is empty. A circular queue lets the pointer wrap back to the start of the array when it reaches the end, so it can reuse cells that have been vacated. In that case you must distinguish an empty queue from a full queue with a counter of elements, because looking only at the two pointers makes these two states look the same.

Worked example: Why recursion uses memory, and when to switch to iteration

A recursive function computes the sum of the numbers from 1 to N. With N equal to 10 it runs fine; with N equal to 500,000 the program stops with a stack overflow error. Explain, write the iterative version, and state when recursion should still be used.

Solution

Why the stack overflows. Each function call places on the call stack a frame containing the parameter N of that call, the local variables, and the address to return to when it completes. In the recursive sum, the call for N cannot return before the call for N minus one returns, so at the deepest point there are N frames at the same time on the stack. With N equal to 10 that is 10 frames, negligible. With N equal to 500,000 it needs 500,000 frames at once, and the memory reserved for the call stack is usually only a few megabytes so it is exceeded — that is the stack overflow error.

The point to recognize. The memory that recursion consumes is proportional to the depth of the chain of calls, not to the amount of data. This is a hidden cost that the iterative version does not have.

The iterative version. TOTAL equals 0 ; K equals 1 ; loop while K is at most N ; TOTAL equals TOTAL plus K ; K equals K plus 1 ; end loop ; output TOTAL. This version uses exactly two variables no matter how large N is, that is, constant-order memory. It runs with N equal to 500,000 or 500 million without any problem.

But do not conclude that iteration is always better. Recursion excels when the problem itself is defined recursively, because then the code mirrors the definition and is much shorter. Three typical groups. The first is tree traversal: a tree is defined as a node with two subtrees, so a recursive traversal takes only three lines whereas an iterative one must manage a stack by hand — which only moves the stack from where the system handles it to where you handle it, and is more error-prone. The second is divide and conquer such as binary search or merge sort. The third is backtracking, when you must try one direction and then return to the previous fork.

The deciding principle. Ask what the maximum recursion depth is. If the depth is proportional to the SIZE of the data — as with the recursive sum here — switch to iteration. If the depth is proportional to the logarithm of the data size or to the height of a balanced tree, then the depth is only a few dozen and recursion is entirely safe, and you should choose it because the code is clearer.

Worked example: Choosing between an array and a linked list for three situations

Choose a data structure for each situation and explain: (a) a lookup table of 26 elements corresponding to 26 letters, looked up very many times; (b) a task list where the user constantly inserts and deletes in the middle, the number of items not known in advance; (c) a queue of files waiting to be printed.

Solution

(a) A lookup table of 26 elements — use an array. Two features decide it. The size is fixed and known in advance, so the linked list's big advantage of growth is useless. And the main operation is direct access by position: from a letter you compute the index immediately and fetch the element in constant time. With a linked list, reaching the 20th element requires passing through the 19 nodes before it, that is, linear time — much slower for an operation repeated very many times.

(b) A task list with insertion and deletion in the middle — use a linked list. Two reasons. First, the number of items is not known in advance, so an array must be over-allocated — wasteful if there are few tasks, and overflowing if there are many. Second, and more important, inserting or deleting in the MIDDLE of an array requires shifting all the elements after it, that is, linear time per operation. With a linked list, an insertion or deletion is just a matter of changing a few pointers, that is, constant time once you are at the right position.

But the condition must be stated, because this is where marks are lost. The statement "inserting into a linked list is constant time" is only true when you are already at the right position. If you must find that position from the start of the list, the search still takes linear time. The real advantage appears when the program already holds a pointer to that position, for example while traversing the list and deleting the elements that satisfy a condition.

(c) A print queue — use a queue implemented with a circular array. The operations are only adding at the rear and removing at the front, never inserting or deleting in the middle, and never accessing by index. A circular array does both operations in constant time, has good access locality because the elements are adjacent in memory, and spends no memory on pointers. Only if the number of waiting files could far exceed any prediction should you switch to a linked-list implementation, trading pointer overhead for unlimited size.

A general decision framework for answering every question of this kind. Ask three questions. Is access by index needed — if so it is almost always an array. Is the size known in advance — if not, lean toward a dynamic structure. What is the most frequent operation — insertion and deletion in the middle lean toward a linked list, while traversal and access by position lean toward an array.

Common mistake

Trap 1 — writing recursion without a base case, or with a base case but a recursive case that does not progress toward it. Both cause infinite recursion and then a stack overflow. When writing recursion in the exam, point out these two parts clearly.
Trap 2 — saying that inserting into a linked list is always constant time. It is only true WHEN you are already at the right position; finding that position still takes linear time because you must walk from the start.
Trap 3 — forgetting that a queue implemented with a straight array reports full even when there is room. After many removals, the start of the array is empty but the rear pointer has reached the boundary. A CIRCULAR queue solves this, and then you need a counter to distinguish empty from full.

Key takeaway

Lesson 1 wrap-up. Four things to take into the exam room. One, recursion needs two parts and uses memory proportional to the call DEPTH; switch to iteration when the depth is proportional to the data size, keep recursion when the depth is only logarithmic or the height of a tree. Two, a stack adds and removes at the same end, a queue at different ends — every other property follows from that. Three, a stack for problems that need to go back, a queue for problems that need fairness in order of arrival, with concrete application examples. Four, three questions for choosing a structure: is access by index needed, is the size known in advance, and what is the most frequent operation.

← Sub-programs, Pre- and Post-conditions, Testing and Debugging · All IB Computer Science lessons · Practice IB Computer Science questions (free, instant scoring) · Binary Trees, Traversals and Choosing a Structure →