algoritmauzmanı
Sign in
TREN
3.4Exam Practice
Lesson 3.4.1

Linked lists: exam questions and answers

This page is the exam practice for the linked lists section. University midterms and finals keep asking the same kinds of linked list questions: conceptual differences, how a given piece of code changes the list, what a function does, and writing a short function. Here you get original questions of each kind with step-by-step answers.

What you will learn
  • Which kinds of linked list questions appear in exams
  • How to solve code tracing and code reading questions on paper, step by step
  • How to write the functions exams often ask for (deletion, reversing, middle node, cycle detection, merging) correctly and completely
25 min

1Conceptual questions

The questions are original, but their types come from the kinds that show up again and again in published midterm and final exams of universities in Turkey and abroad. Solve each question yourself first, then open the box and compare. The code uses the node structure of this section's lessons: struct Node { int data; struct Node* next; };, plus prev in doubly linked lists.

1Compare an array and a singly linked list in memory layout, access, insertion and extra memory. When would you choose each?Midterm · concepts

An array keeps its elements in , while a linked list keeps each element in its own and connects the nodes with pointers. Every difference follows from these two layouts.

PropertyArraySingly linked list
Memory layoutElements side by sideNodes scattered, ordered by links
Access to the k-th elementO(1): the address is computedO(n): walk k steps from the front
Insert or delete at the frontO(n): elements shiftO(1): two links change
SizeFixed up frontGrows as nodes are added
Extra memoryNoneOne pointer per node

Choose an array when you mostly reach elements by index and the size is roughly known. Choose a linked list when the number of elements is not known in advance and you often insert or delete at the front or in the middle. Details: Introduction to linked lists.

2Compare singly, doubly and circular linked lists. In each one, what does the last node's next field point to?Midterm · concepts

The three kinds differ in how many links a node carries and where the last node points.

KindLinks in a nodeLast node's nextDirection of traversal
Singly linkednextNULLForward only
Doubly linkedprev and nextNULL (the first node's prev is NULL too)Forward and backward
Circular (singly)nextThe first node (head)Forward, in a ring

In a doubly linked list, a node whose address you know is deleted in without searching for the previous node; the price is one extra pointer per node. A circular list has no NULL, so traversal stops when it gets back to the start, or else the loop never ends (Traversal and where the loop ends).

3In a singly linked list you are given only a pointer p to the node to delete; you are not given head. Can you delete the node? When can you not?Final · concepts

You cannot unlink the node itself, because that needs a change to the previous node's next and you have no way to reach the previous node. But you can get the same list as a result: copy the next node's value into p, then delete the next node.

void deleteGivenNode(struct Node* p) {  // p must not be the last node    struct Node* next = p->next;    p->data = next->data;             // copy the next node's value    p->next = next->next;             // unlink the next node    free(next);}

Example: in 5 → 8 → 2 → 9, p points to 8. The value 2 is copied into p, the node of 2 is skipped and the list becomes 5 → 2 → 9. This trick fails when p is the last node: there is no next node to copy, and setting the previous node's next to NULL again needs head.

4What is wrong with the delete-from-head function below? What is the bug called? Write the corrected version.Midterm · find the bug

After free(*head) the node's memory no longer belongs to the program. The next line reads that same node's next field; this is use of a and the behavior is undefined. The program may seem to work one time and crash the next.

void deleteHead(struct Node** head) {    if (*head == NULL) return;    free(*head);    *head = (*head)->next;     // BUG: reads a node that was freed}

The right order: keep the address, move head forward, free last.

void deleteHead(struct Node** head) {    if (*head == NULL) return;    struct Node* temp = *head;     // keep the address first    *head = temp->next;            // then move head forward    free(temp);                    // free it last}

The opposite is also a bug: if you write *head = (*head)->next; and never call , no pointer to the old head is left and its memory is never returned. That is a . Details: Deleting from the head.

5True or false? "Inserting an element into a singly linked list of n nodes always takes O(n)." Explain.Midterm · true or false

False. The time depends on where you insert and which pointer you already hold.

  • Inserting at the head is always : the new node links to head, and head moves to the new node.
  • Inserting after a node whose address you know is O(1): only two links change.
  • Inserting at position k is O(k): first you walk to the node at position k-1. In the worst case that is .
  • Inserting at the end is O(n) without a tail, O(1) with one.

So "always" is wrong; O(n) appears only when you have to search for the position.

2Code tracing questions

In this kind of question you get a list and a short piece of code, and you are asked what the list or the output looks like afterwards. Draw boxes and arrows on paper and change only one arrow per line.

Code for the next question (list: head → 4 → 8 → 15 → 16 → 23 → NULL):

struct Node* p = head->next;struct Node* q = p->next->next;p->next = q;q->data = q->data + p->data;head = p;
6After the code above runs, what is printed when the list is traversed from head? Which nodes can no longer be reached?Midterm · code tracing

The list becomes 8 → 24 → 23. No pointer is left to the nodes holding 4 and 15; since free is never called, they are a memory leak.

LineWhat happensState
1p points to the second nodep → 8
2p->next is 15, its next is 16q → 16
38's link is turned to 16, 15 is skipped4 → 8 → 16 → 23
416 + 8 = 244 → 8 → 24 → 23
5head moves to 8, 4 is left outside8 → 24 → 23
7Starting from an empty list, these operations run in order: insertAtHead(5), insertAtEnd(9), insertAtHead(2), insertAt(position 1, 7), deleteHead(), deleteTail(), insertAtEnd(4). Write the list after each step. Positions start at 0.Midterm · operation tracing

The final list is 7 → 5 → 4. Writing down every step keeps you from miscounting the position in the middle insertion.

OperationList
insertAtHead(5)5
insertAtEnd(9)5 → 9
insertAtHead(2)2 → 5 → 9
insertAt(1, 7)2 → 7 → 5 → 9
deleteHead()7 → 5 → 9
deleteTail()7 → 5
insertAtEnd(4)7 → 5 → 4

Inserting at position 1 means the new node ends up at index 1: it goes right after 2. See Inserting at a position.

Code for the next question:

struct Node* p = head;while (p != NULL && p->next != NULL) {    printf("%d ", p->data);    p = p->next->next;}
8If the list is 3 → 6 → 9 → 12 → 15, what does the loop above print? What is printed if 18 is added at the end?Midterm · code tracing

With five nodes the output is 3 9; after adding 18 it is 3 9 15. p skips two nodes each round, so only the values at even indexes are printed. The loop condition needs both p and p->next to be non-NULL.

  1. Five nodes: p = 3, a next node exists, 3 is printed, p jumps to 9.
  2. p = 9, the next node 12 exists, 9 is printed, p jumps to 15.
  3. p = 15, p->next is NULL, so the loop ends; 15 is not printed.
  4. Six nodes: 3 and 9 are printed, p = 15, the next node 18 exists, 15 is printed, p = 18->next = NULL and the loop ends.

The order of the condition matters: p != NULL is checked first, so p->next is never read while p is NULL.

Code for the next question (doubly linked list: head → 10 ⇄ 20 ⇄ 30 ⇄ 40):

// p points to the node holding 30p->prev->next = p->next;p->next->prev = p->prev;free(p);
9After the code above runs, what is printed when the list is traversed from the end to the front? What would happen if p pointed to the last node (40)?Final · code tracing

Traversing from the end prints 40 20 10. The first line turns 20's next to 40, the second turns 40's prev to 20; 30 is skipped in both directions and freed.

If p were the last node, p->next would be NULL and the second line would try to write to NULL->prev: the program crashes. If p were the first node, the first line would crash instead because p->prev is NULL, and head would not be updated either. That is why a general delete function checks both ends with if; see the last code writing question on this page and Deleting from a doubly linked list.

3Code reading questions

Here you get a function and are asked what it does. Pick a small list, run the function by hand, then state the result in one sentence.

int f(struct Node* h) {    if (h == NULL)        return 0;    return (h->data % 2 == 0) + f(h->next);}
10What does the function f above do? If the list is 7 → 4 → 10 → 3 → 6, what does f(head) return?Midterm · code reading

f counts the nodes with even values using , and for this list it returns 3. In C, h->data % 2 == 0 gives 1 when true and 0 when false; each node adds its share to the result for the rest of the list.

CallThis node's shareReturns
f(7)00 + 3 = 3
f(4)11 + 2 = 3
f(10)11 + 1 = 2
f(3)00 + 1 = 1
f(6)11 + 0 = 1
f(NULL)0 (base case)
void g(struct Node* h) {    if (h == NULL)        return;    printf("%d ", h->data);    g(h->next);    printf("%d ", h->data);}
11What does the function g above print for the list 1 → 2 → 3?Final · code reading

The output is 1 2 3 3 2 1. The printf before the recursive call prints the nodes front to back on the way in, and the printf after the call prints them back to front on the way out.

  1. g(1): prints 1, calls g(2).
  2. g(2): prints 2, calls g(3).
  3. g(3): prints 3, g(NULL) returns at once, prints 3.
  4. Back in g(2): prints 2.
  5. Back in g(1): prints 1.

If only the second printf is kept, the function prints the list in reverse without changing it. The pending calls wait on the ; for a list of n nodes the extra memory is O(n). Details: Reversing (recursive).

int findMax(struct Node* head) {    int m = 0;    struct Node* p = head;    while (p != NULL) {        if (p->data > m)            m = p->data;        p = p->next;    }    return m;}
12What is the function findMax above trying to do? For which list does it give a wrong result? Fix it.Midterm · code reading

The function tries to find the largest value in the list, but since m starts at 0 it gives a wrong result when all values are negative: for -5 → -2 → -9 it returns 0 instead of -2. It also returns 0 for an empty list, which has no largest element at all.

The fix: start m with the first node's value and compare from the second node on. The caller checks for an empty list.

int findMax(struct Node* head) {      // head must not be NULL    int m = head->data;    struct Node* p = head->next;    while (p != NULL) {        if (p->data > m)            m = p->data;        p = p->next;    }    return m;}
void h(struct Node** head) {    if (*head == NULL || (*head)->next == NULL)        return;    struct Node* prev = NULL;    struct Node* p = *head;    while (p->next != NULL) {        prev = p;        p = p->next;    }    prev->next = NULL;    p->next = *head;    *head = p;}
13What does the function h above turn the list 1 → 2 → 3 → 4 into? Say in one sentence what it does.Final · code reading

The list becomes 4 → 1 → 2 → 3: the function moves the last node to the front. For an empty list or a single node it does nothing.

  1. When the loop ends, p points to the last node (4) and prev to the one before it (3).
  2. prev->next = NULL: 3 becomes the new last node.
  3. p->next = *head: 4 links to the old head, 1.
  4. *head = p: the list now starts at 4.

Finding the last node means walking from the front, so the function takes .

4Code writing questions

In code writing questions, points are lost on edge cases: the empty list, a single node, the case where the head changes, and the last node. Under each answer you can read how these cases are handled. In C, functions that may change head take struct Node** head.

14Write deleteValue(struct Node** head, int value), which deletes the first node holding the given value.Midterm · code writing

Walk the list with prev and temp together. When the value is found, point the previous node past the deleted one; if the deleted node is the head, move head forward.

void deleteValue(struct Node** head, int value) {    struct Node* temp = *head;    struct Node* prev = NULL;    while (temp != NULL && temp->data != value) {        prev = temp;        temp = temp->next;    }    if (temp == NULL) return;            // value not in the list    if (prev == NULL)        *head = temp->next;              // deleting the head    else        prev->next = temp->next;         // a middle or last node    free(temp);}
  • Empty list or value missing: the loop ends when temp is NULL, and the list stays the same.
  • Deleting the head: prev stays NULL, head moves to the second node.
  • Deleting the last node: prev->next becomes NULL.

For deleting by position, see Deleting from the middle.

15Write the function insertAt, which inserts a new node at a given position (starting from 0) in a singly linked list. For an invalid position the list must stay the same.Midterm · code writing

Position 0 is insertion at the head, and head changes. For other positions you walk to the node at position-1 and link the new node after it. The order of the links matters: first the new node's next, then the previous node's next.

void insertAt(struct Node** head, int pos, int value) {    if (pos < 0) return;                      // invalid position    if (pos == 0) {                           // insert at the head        struct Node* node = malloc(sizeof(struct Node));        node->data = value;        node->next = *head;        *head = node;        return;    }    struct Node* temp = *head;    for (int i = 0; i < pos - 1 && temp != NULL; i++)        temp = temp->next;                    // go to the node at pos-1    if (temp == NULL) return;                 // position past the end    struct Node* node = malloc(sizeof(struct Node));    node->data = value;    node->next = temp->next;                  // link the new node first    temp->next = node;                        // then point the previous one to it}

If the two lines are swapped, so that temp->next = node comes first, the address of the rest of the list is lost. If the position equals the number of elements, the node goes at the end; if it is larger, temp becomes NULL and the function returns. Details and drawing: Inserting at a position.

16Write a function that reverses a singly linked list in place, without allocating new nodes, and trace it for 1 → 2 → 3.Final · code writing

Three pointers are used: prev, curr and next, which keeps the rest of the list. Each round flips curr's link backward and moves both forward by one. At the end prev is the new head.

void reverse(struct Node** head) {    struct Node* prev = NULL;    struct Node* curr = *head;    while (curr != NULL) {        struct Node* next = curr->next;  // keep the rest        curr->next = prev;               // flip the link        prev = curr;        curr = next;    }    *head = prev;}
RoundLink flippedprevcurr
StartNULL1
11 → NULL12
22 → 123
33 → 23NULL

The loop ends, head becomes 3 and the list reads 3 → 2 → 1 → NULL. Time , extra memory O(1). Step-by-step drawing: Reversing (iterative).

17Write a function that finds the middle node by traversing the list only once. Which node is returned when the number of nodes is even?Final · code writing

Use two pointers, slow and fast: slow moves one step, fast moves two. When fast reaches the end, slow is exactly in the middle.

struct Node* middle(struct Node* head) {    struct Node* slow = head;    struct Node* fast = head;    while (fast != NULL && fast->next != NULL) {        slow = slow->next;            // one step        fast = fast->next->next;      // two steps    }    return slow;                      // NULL for an empty list}

For 1 → 2 → 3 → 4 → 5 the function returns 3. For 1 → … → 6 there are two middles (3 and 4); this code returns the second one, 4. If the question asks for the first middle, the loop condition becomes fast->next != NULL && fast->next->next != NULL (with the empty list checked separately). Time O(n), extra memory O(1).

18Write a function that finds whether a singly linked list has a cycle (some node's next points back to an earlier node), using O(1) extra memory.Final · code writing

Floyd's method: the slow pointer moves one step, the fast pointer two. Without a cycle, the fast one reaches NULL. With a cycle, both enter the loop and the fast one closes the gap by one node each round, so they are bound to meet at the same node.

bool hasCycle(struct Node* head) {    struct Node* slow = head;    struct Node* fast = head;    while (fast != NULL && fast->next != NULL) {        slow = slow->next;        fast = fast->next->next;        if (slow == fast)            return true;              // they met at the same node    }    return false;                     // the fast pointer reached NULL}

Keeping the visited nodes in a set also works, but needs O(n) extra memory. Floyd's method takes O(n) time and uses no memory beyond two pointers. A plain while (p != NULL) traversal never ends on a list with a cycle; noticing that is the point of the question.

19Write a function that finds the k-th node from the end (k = 1 is the last node) in one pass. If the list has fewer than k nodes, return NULL.Midterm · code writing

Keep a gap of k nodes between two pointers: move the leader k steps first, then walk both together. When the leader is NULL, the trailer is at the k-th node from the end.

struct Node* kthFromEnd(struct Node* head, int k) {    // k >= 1    struct Node* lead = head;    for (int i = 0; i < k; i++) {        if (lead == NULL)            return NULL;              // the list has fewer than k nodes        lead = lead->next;            // move the leader k steps ahead    }    struct Node* trail = head;    while (lead != NULL) {            // walk both together        lead = lead->next;        trail = trail->next;    }    return trail;}

For 1 → 2 → 3 → 4 → 5 and k = 2: the leader reaches 3; walking together for three steps, the trailer is at 4 when the leader is NULL. With k = 5 the trailer stays at 1; with k = 6 the first loop returns NULL. Counting the length first and then walking n - k steps from the front is also correct, but it takes two passes.

20Write a Java function that merges two singly linked lists sorted in ascending order into one sorted list without allocating new nodes.Final · code writing

Put a temporary dummy node in front of the result and track the end of the result with tail. At each step, link the smaller of the two front nodes to the end. When one list runs out, attach the rest of the other as it is.

static Node merge(Node a, Node b) {    Node dummy = new Node(0);         // a temporary node in front of the result    Node tail = dummy;    while (a != null && b != null) {        if (a.data <= b.data) {            tail.next = a;            a = a.next;        } else {            tail.next = b;            b = b.next;        }        tail = tail.next;    }    tail.next = (a != null) ? a : b;  // attach the rest as it is    return dummy.next;}

Merging 1 → 4 → 9 and 2 → 4 → 6 → 11 gives 1 → 2 → 4 → 4 → 6 → 9 → 11. The dummy node removes the need for a separate if for the first node of the result. For lists of length m and n the time is O(m + n) and the extra memory O(1). Using <= on ties puts the first list's element first.

21Write a Python function that removes repeated values from a sorted list, keeping one of each value.Midterm · code writing

Since the list is sorted, the copies sit next to each other. Compare each node with the next one: if they are equal, skip the next one and stay where you are; if they differ, move on.

def remove_duplicates(head):    temp = head    while temp is not None and temp.next is not None:        if temp.next.data == temp.data:            temp.next = temp.next.next       # skip the copy        else:            temp = temp.next                 # move on if different    return head

The list 2 → 2 → 5 → 7 → 7 → 7 → 9 becomes 2 → 5 → 7 → 9. When a copy is skipped, temp does not move; with three 7s that is the only way the second and third copies both go. In Python the skipped node is reclaimed by the garbage collector; in C you must call free on every skipped node. Time O(n).

22Write a function that counts the nodes of a circular singly linked list.Midterm · code writing

A circular list has no NULL; traversal stops when it gets back to the start. The body must run at least once, or else the loop is never entered because temp == head at the start. That is why do-while is used and the empty list is checked separately.

int count(struct Node* head) {    if (head == NULL) return 0;       // empty list    int total = 0;    struct Node* temp = head;    do {        total++;        temp = temp->next;    } while (temp != head);           // stop when back at the start    return total;}

In a circular list with one node, the node points to itself: the body runs once, temp is head again and 1 is returned. Writing the condition as temp != NULL is a common mistake: on a circular list the loop never ends. See Traversal and where the loop ends.

23Write deleteNode(struct Node** head, struct Node* target), which deletes a node of a doubly linked list given its address.Final · code writing

In a doubly linked list there is no need to search for the previous node: target->prev already points to it. Two links are updated, but each may be NULL at the ends, so each is guarded with an if.

void deleteNode(struct Node** head, struct Node* target) {    if (*head == NULL || target == NULL) return;    if (target->prev != NULL)        target->prev->next = target->next;    else        *head = target->next;                 // deleting the head    if (target->next != NULL)        target->next->prev = target->prev;    free(target);}
  • Head node: prev is NULL, and head moves to the next node.
  • Last node: next is NULL, and only the previous node's next becomes NULL.
  • Single node: both conditions hold, and head becomes NULL.

The operation takes ; in a singly linked list the same job needs O(n) to find the previous node. See Deleting from a doubly linked list.

5Complexity questions

24Give, in a table, the time complexity of the operations below for an array, a singly linked list with only head, a singly linked list with head and tail, and a doubly linked list with head and tail.Midterm · complexity

Every difference in the table rests on two questions: do elements shift, and do you have to walk to reach the link you need to change?

OperationArraySingly (head)Singly (head + tail)Doubly (head + tail)
Insert at the frontO(n)O(1)O(1)O(1)
Insert at the endO(1) if there is roomO(n)O(1)O(1)
Delete from the frontO(n)O(1)O(1)O(1)
Delete from the endO(1)O(n)O(n)O(1)
Access the k-th elementO(1)O(n)O(n)O(n)
Search for a valueO(n)O(n)O(n)O(n)
Delete a node whose address you knowO(n)O(n)O(n)O(1)

In an array, inserting and deleting at the front shift the elements, so they take O(n). In a linked list, search is O(n) even when the values are sorted: binary search needs to jump to the middle element, and a linked list cannot make that jump.

25In a singly linked list, a tail pointer makes insertion at the end O(1). Why is deleting from the end still O(n)?Midterm · complexity

To delete the last node you must set the next-to-last node's next to NULL and move tail to it. tail points to the last node, but a singly linked list has no link going back from the last node; to find the previous one you walk from the front.

Inserting at the end only changes the last node itself (tail->next = node), so tail is enough. To make deleting from the end O(1) as well, use a doubly linked list: tail->prev gives the previous node at once. See Deleting from the end.

6Try it

When looking for the middle node with slow and fast pointers, why is the loop condition fast != NULL && fast->next != NULL?

Show the answer

The answer is A. Before fast->next->next is read, both fast and fast->next must be non-NULL. The slow pointer is behind the fast one, so it is safe on its own.

What happens if you traverse a circular list with while (temp != NULL)?

Show the answer

The answer is B. The last node links back to the front; temp never becomes NULL. Traversal is stopped when you get back to head.

Lessons you mark show up in the curriculum. If you are signed in, they are saved to your account too.