Embercode
✕
Linked ListsQuick quiz

Pointer bug hunt

9 questions. Covers Debugging lab: pointer bugs in lists.

Questions 1 to 5 of 9

  1. 1. What is wrong with this count_nodes? ``cpp int count_nodes(const Node* head) { if (head == nullptr) return 0; int count = 0; for (const Node* cur = head; cur->next != nullptr; cur = cur->next) ++count; return count; } ``
  2. 2. A caller runs this code. What goes wrong? ``cpp void remove_first(Node* head, int target) { Node* prev = nullptr; Node* cur = head; while (cur != nullptr && cur->value != target) { prev = cur; cur = cur->next; } if (cur == nullptr) return; if (prev == nullptr) head = cur->next; else prev->next = cur->next; delete cur; } ``
  3. 3. Which line is the bug in this remove_below? ``cpp void remove_below(Node*& head, int limit) { Node* prev = nullptr; Node* cur = head; while (cur != nullptr) { if (cur->value < limit) { if (prev == nullptr) head = cur->next; else prev->next = cur->next; delete cur; cur = cur->next; } else { prev = cur; cur = cur->next; } } } ``
  4. 4. What does this insert_after do when p is the node holding 5 in the list 5 -> 6 -> 7? ``cpp void insert_after(Node* p, int value) { Node* fresh = new Node{value}; p->next = fresh; fresh->next = p->next; } ``
  5. 5. What does this contains do when it is called as contains(h, 9) on the list 5 -> 6 -> 7? ``cpp bool contains(Node* head, int target) { for (Node* cur = head; cur != nullptr; cur = cur->next) { if (cur->value = target) return true; } return false; } ``

5 question(s) left on this page.