Embercode
✕
Linked ListsQuick quiz

Sentinels and removal

8 questions. Covers Remove every occurrence of a value.

Questions 1 to 5 of 8

  1. 1. In removeAll from the lesson, why is Node* next = cur->next; written before the if block and not after the delete?
  2. 2. A DList with a sentinel has no null checks at the ends. Why does popFront still start with if (empty()) return false;?
  3. 3. This program is the lesson's ring with a sentinel. What does it print? ``cpp #include <iostream> struct Node { int value; Node* prev; Node* next; }; Node sentinel{0, nullptr, nullptr}; void insertAfter(Node* where, int v) { Node* n = new Node{v, where, where->next}; where->next->prev = n; where->next = n; } void erase(Node* n) { n->prev->next = n->next; n->next->prev = n->prev; delete n; } int main() { sentinel.next = &sentinel; sentinel.prev = &sentinel; insertAfter(sentinel.prev, 5); insertAfter(sentinel.prev, 6); insertAfter(sentinel.prev, 7); erase(sentinel.next->next); insertAfter(&sentinel, 4); int count = 0; for (Node* p = sentinel.next; p != &sentinel; p = p->next) { ++count; } std::cout << "front " << sentinel.next->value << ", back " << sentinel.prev->value << ", count " << count << '\n'; return 0; } ``
  4. 4. What does this program print? ``cpp #include <iostream> struct Node { int value; Node* next; }; void removeAll(Node*& head, int target) { Node* prev = nullptr; Node* cur = head; while (cur != nullptr) { Node* next = cur->next; if (cur->value == target) { if (prev == nullptr) { head = next; } else { prev->next = next; } delete cur; } else { prev = cur; } cur = next; } } int main() { Node* head = nullptr; for (int v : {7, 2, 5, 2, 2}) { head = new Node{v, head}; } removeAll(head, 2); int count = 0; int sum = 0; for (Node* p = head; p != nullptr; p = p->next) { ++count; sum += p->value; } std::cout << count << " nodes, sum " << sum << '\n'; return 0; } ``
  5. 5. This loop should remove every target value. On the list 2, 2, 1 with target 2 it writes into freed memory. What is the bug? ``cpp Node* next = cur->next; if (cur->value == target) { if (prev == nullptr) head = next; else prev->next = next; delete cur; } prev = cur; cur = next; ``

5 question(s) left on this page.