Chapter 4: Linked Lists

Data Structures and Algorithms with C · Study Questions
Nodes and linksInsertion and deletionLeaks and dangling pointersMergingFloyd and the middle nodeCircular and doubly linkedHeader nodeThe avail list
Sercan KÜLCÜ · Giresun University · Computer Engineering

Multiple Choice · Why Lists?

Question 1: Fast in an Array, Slow in a List

Which of the following operations takes O(1) on an array but O(n) on a singly linked list (with only a head pointer)?

D: The address of a[i] in an array is computed as α + i·s. In a list the address of the i-th node cannot be computed; i links are followed from the head: O(i). The other three are O(1) in a list, but O(n) in an array because elements must be shifted.

Multiple Choice · Singly Linked List

Question 2: The Head Passed by Value

With list = 7 → 2, the faulty version below is called as insert_front(list, 5). What happens after the call?

void insert_front(node_ptr head, int x) {
  node_ptr temp = malloc(sizeof *temp);
  if (temp == NULL) return;
  temp->data = x;
  temp->link = head;
  head = temp;
}

B: head is a copy of list in main. head = temp changes only the copy; when the function returns, the new node's address is kept nowhere: the list stays 7 → 2 and the node holding 5 is a memory leak. A routine that changes the head must take node_ptr *head and be called with &list.

Output Question · Singly Linked List

Question 3: A Sequence of Operations

What does this fragment print, using insert_front, insert_back, delete_key, nth and search from the slides?

node_ptr L = NULL, p;
insert_front(&L, 3);
insert_front(&L, 8);
insert_back(&L, 5);
delete_key(&L, 8);
insert_back(&L, 8);
print_list(L);
printf("%d ", nth(L, 1)->data);
p = search(L, 9);
printf("%s\n", p ? "found" : "NULL");
Show answer
3 5 8
5 NULL
  • insert_front 3 → 3; insert_front 8 → 8 3; insert_back 5 → 8 3 5.
  • delete_key 8: the first node is deleted (prev == NULL) → *head = p->link: 3 5.
  • insert_back 8 → 3 5 8. nth(L, 1) is 0-based: 5. 9 is not in the list → search returns NULL.

Multiple Choice · Singly Linked List

Question 4: The Order of Conditions

The loop of search is written as while (p->data != x && p != NULL). In which case does undefined behavior occur?

A: If x is absent, p finally becomes NULL and the first part of the condition reads NULL->data. If x is in the list, the loop stops before p becomes NULL and the bug stays invisible; so it shows up only in the ‘not found’ test. The correct order is p != NULL && p->data != x: short-circuit evaluation protects the right-hand side.

Spot the Bug · Singly Linked List

Question 5: Access After free

What is the bug in this function that empties a list? How is it written correctly?

void clear_list(node_ptr *list) {
  node_ptr p;
  for (p = *list; p != NULL; p = p->link)
    free(p);
  *list = NULL;
}
Show answer

The increment part of the loop, p = p->link, runs after free(p): the link field of a released node is read. This is use after free (undefined behavior); if the memory has been reused, the loop may jump to a random address.

void clear_list(node_ptr *list) {
  while (*list != NULL) {
    node_ptr p = *list;
    *list = p->link;  /* advance */
    free(p);  /* release */
  }
}

Rule: the next address is saved before free. At the end *list is NULL; no dangling pointer remains.

Coding Question · Singly Linked List

Question 6: The k-th Node from the End

Write a function node_ptr kth_from_end(node_ptr head, int k) that finds the k-th node from the end (k = 1 is the last node) in a single pass. It should return NULL if the list is shorter than k.

Show answer
node_ptr kth_from_end(node_ptr head, int k) {
  node_ptr fast = head, slow = head;
  while (k-- > 0) {             /* k steps ahead */
    if (fast == NULL) return NULL;
    fast = fast->link;
  }
  while (fast != NULL) {       /* together */
    fast = fast->link;
    slow = slow->link;
  }
  return slow;
}

When fast reaches NULL, slow is exactly k nodes behind it. For 10 → 20 → … → 60: k = 1 → 60, k = 2 → 50, k = 6 → 10, k = 7 → NULL. O(n) time, O(1) extra memory.

Step-by-Step Trace · Classic Routines

Question 7: Merging Two Sorted Lists

sorted_merge merges 1 → 4 → 6 and 2 → 3 → 7 without allocating nodes. How do the links change, step by step?

H146237?tailab

The head variable on the stack acts as a header: tail starts linked to it, so the first node needs no special case.

H146237tailab

1 ≤ 2: 1 is linked to the result, a advances.

H146237tailab

4 > 2: the link of 1 is redirected to 2, b advances.

H146237tailab

4 > 3: 3 is linked (it was already behind 2).

H146237tailab

4 ≤ 7: the link of 3 is redirected to 4.

H146237a = NULLtailb

6 ≤ 7: 6 is linked, a becomes NULL; the loop ends.

H146237a = NULLtailb

The rest of b is attached with a single link. Result head.link: 1 → 2 → 3 → 4 → 6 → 7. No malloc at all; O(n + m) time, O(1) extra memory.

node_ptr sorted_merge(node_ptr a, node_ptr b) {
  struct node head;           /* temporary header */
  node_ptr tail = &head;
  while (a != NULL && b != NULL) {
    if (a->data <= b->data) {
      tail->link = a; a = a->link;
    } else {
      tail->link = b; b = b->link;
    }
    tail = tail->link;
  }
  tail->link = (a != NULL) ? a : b;
  return head.link;
}

Multiple Choice · Classic Routines

Question 8: The Tortoise and the Hare

The list is 1 → 2 → 3 → 4 → 5 → 6 and the link of 6 points to 3. In has_cycle from the slides, at which node do slow and fast meet?

C: Rounds (slow, fast): (2, 3), (3, 5), (4, 3), (5, 5) → they meet at node 5 in round 4. Although the cycle entry is 3, the meeting point is usually not the entry; finding the entry needs an extra step.

Coding Question · Classic Routines

Question 9: The Entry of the Cycle

Extend Floyd's algorithm: write cycle_start, which returns the cycle's entry node if there is a cycle and NULL otherwise. What does it return for the list 1 → … → 6 with 6 linked back to 3?

Show answer
node_ptr cycle_start(node_ptr head) {
  node_ptr slow = head, fast = head;
  while (fast != NULL && fast->link != NULL) {
    slow = slow->link; fast = fast->link->link;
    if (slow == fast) {          /* they met */
      slow = head;               /* one back to head */
      while (slow != fast) {     /* one step each */
        slow = slow->link; fast = fast->link;
      }
      return slow;
    }
  }
  return NULL;
}

In the example they meet at 5. slow goes back to the head and fast stays at 5; both advance one step at a time: slow 1 → 2 → 3, fast 5 → 6 → 3 → node 3. The distance from the head to the entry equals the distance from the meeting point to the entry along the cycle, up to multiples of the cycle length. O(n) time, O(1) memory.

Step-by-Step Trace · Classic Routines

Question 10: The Middle Node of an Even-Length List

Which node does middle return for the list 1 → 2 → 3 → 4 → 5 → 6? How must the condition change so that it returns the first middle (3)?

123456slow,fast

Both start at the head. The list has an even length: 6 nodes.

123456slowfast

Round 1: slow moves 1 step, fast moves 2.

123456slowfast

Round 2.

123456slowfast = NULL

Round 3: 5 → 6 → NULL. Because fast is NULL, the condition is false by short-circuit evaluation.

123456slowfast = NULL

It returns the second middle, 4. Had the condition fast->link->link != NULL been added, the loop would stop after 2 rounds and the first middle, 3, would be returned.

node_ptr middle(node_ptr head) {
  node_ptr slow = head, fast = head;
  while (fast != NULL &&
         fast->link != NULL) {
    slow = slow->link;
    fast = fast->link->link;
  }
  return slow;
}

Multiple Choice · Circular and Doubly Linked

Question 11: while Instead of do-while

In the circular list 3 → 5 → 8 → (3), last points to 8. If this loop is written instead of the do-while in c_length, what does the function return?

int n = 0;
node_ptr p = last;
while (p != last) {
  n++;
  p = p->link;
}
return n;

C: It starts with p = last and the condition p != last is false at the first check: the body never runs and 0 is returned. Traversal of a circular list ends when we come back to the start; the body must run at least once, which is why do-while is used. D would be correct if the condition were p != NULL.

Output Question · Circular and Doubly Linked

Question 12: Insertion into a Circular List

What does this fragment print, using c_insert_front from the slides? (new_node allocates a node.)

node_ptr last = NULL, t, p;
c_insert_front(&last, new_node(4));
t = new_node(7);
c_insert_front(&last, t); last = t;
c_insert_front(&last, new_node(1));
t = new_node(9);
c_insert_front(&last, t); last = t;
p = last->link;
do {
  printf("%d ", p->data);
  p = p->link;
} while (p != last->link);
printf("last=%d\n", last->data);
Show answer

Output: 1 4 7 9 last=9.

  • 4 into the empty list: it points to itself, last = 4.
  • 7 is inserted at the front, then last = t: insertion at the back → 4 7, last = 7.
  • 1 at the front: last->link is now 1 → 1 4 7.
  • 9 is inserted at the front and made last → 1 4 7 9, last = 9.

Insertion at the front and at the back is the same link operation; the only difference is updating last. Both are O(1).

Multiple Choice · Circular and Doubly Linked

Question 13: Merging Circular Lists

Two circular lists with n and m nodes are held by the pointers last1 and last2. What does it cost to merge them into one circular list?

D: first1 = last1->link; last1->link = last2->link; last2->link = first1; and the new last is last2: three links, no traversal. In a plain singly linked list, concatenation is O(n) because the end of the first list must be found; a last pointer removes that walk.

Multiple Choice · Circular and Doubly Linked

Question 14: The Order of the Links

In a doubly linked list with a header, H ⇄ 4 ⇄ 8 ⇄ H; p = 4 and temp = 6. The last two lines of dinsert have been swapped. Which links stay wrong?

temp->llink = p;
temp->rlink = p->rlink;
p->rlink = temp;
p->rlink->llink = temp;

A: When p->rlink = temp runs first, p->rlink->llink is now the llink of 6, not of 8: 6->llink = 6, while 8->llink stays at 4. The forward direction (4 → 6 → 8) is correct; going backward, 8 jumps to 4. The invariant p == p->rlink->llink is broken.

Multiple Choice · Circular and Doubly Linked

Question 15: What the Header Node Buys

Which statement is true for a singly linked list with a header node?

B: The header is never deleted and carries no data; an empty list consists of the header alone, and the head pointer always points to it. Because every real node has a predecessor, h_insert_sorted takes the header by value; the special case of *head and prev == NULL disappears.

Step-by-Step Trace · Memory Management

Question 16: The Available-Node List

With an empty avail, the operations in the comment are performed in order. How many malloc calls are made, which nodes do d and e get, and what is left in avail at the end?

availNULLin usea=N1b=N2c=N3malloc calls: 3

avail is empty: all three nodes come from malloc (N1, N2, N3).

availN1N2in usec=N3malloc calls: 3

ret(b), ret(a): instead of free, they are added to the front of avail. The last one returned (N1) goes first: avail is a stack.

availNULLin usec=N3d=N1e=N2malloc calls: 3

d = get → N1 (a’s old node), e = get → N2. No malloc call.

availNULLin usec=N3d=N1e=N2f=N4malloc calls: 4

avail is empty again: the 4th malloc is for f.

availN1N3in usee=N2f=N4malloc calls: 4

ret(c), ret(d): avail is N1 → N3. 4 mallocs in total, no free at all; the 2 nodes in avail do not return to the heap until the program ends.

node_ptr get_node(void) {
  node_ptr p;
  if (avail != NULL) {
    p = avail; avail = avail->link;
  } else {
    p = malloc(sizeof *p);
    if (p == NULL) exit(1);
  }
  return p;
}
void ret_node(node_ptr p) {
  p->link = avail; avail = p;
}
/* a=get(); b=get(); c=get();
   ret(b); ret(a);
   d=get(); e=get(); f=get();
   ret(c); ret(d);  */

The End

Chapter 4: Linked Lists: Study Questions
Lecture slides: Chapter 4: Linked Lists · Lecture notes
1 / 1 Sercan KÜLCÜ. All rights reserved.