Embercode
✕
Linked ListsQuick quiz

Mixed review of lists

8 questions. Covers Reverse in groups of k.

Questions 1 to 5 of 8

  1. 1. In the length method for the intersection of two lists, why is the longer list moved forward before the two pointers are compared?
  2. 2. Why does swap_pairs_iterative start with a dummy node in front of the head?
  3. 3. In reverse_one_group, the walk from group_prev runs off the end of the list. What does the function return, and what happens to the list?
  4. 4. What does this program print? ``cpp #include <iostream> struct Node { int value; Node* next = nullptr; }; Node* rotate_right(Node* head, int k) { if (head == nullptr || head->next == nullptr) return head; int n = 1; Node* tail = head; while (tail->next != nullptr) { tail = tail->next; ++n; } int shift = k % n; if (shift == 0) return head; tail->next = head; int steps = n - shift - 1; Node* new_tail = head; for (int i = 0; i < steps; ++i) new_tail = new_tail->next; Node* new_head = new_tail->next; new_tail->next = nullptr; return new_head; } int main() { Node* head = nullptr; for (int v = 6; v >= 1; --v) head = new Node{v, head}; head = rotate_right(head, 8); for (const Node* p = head; p != nullptr; p = p->next) { std::cout << p->value << (p->next ? " " : "\n"); } } ``
  5. 5. What does this program print? ``cpp #include <iostream> struct Node { int value; Node* next; }; Node* reverse_one_group(Node* group_prev, int k) { Node* kth = group_prev; for (int i = 0; i < k && kth != nullptr; ++i) kth = kth->next; if (kth == nullptr) return nullptr; Node* group_next = kth->next; Node* old_first = group_prev->next; Node* prev = group_next; Node* cur = old_first; while (cur != group_next) { Node* nxt = cur->next; cur->next = prev; prev = cur; cur = nxt; } group_prev->next = kth; return old_first; } Node* reverse_in_groups(Node* head, int k) { Node dummy{0, head}; Node* group_prev = &dummy; while (true) { Node* last = reverse_one_group(group_prev, k); if (last == nullptr) break; group_prev = last; } return dummy.next; } int main() { Node* head = nullptr; for (int v = 6; v >= 1; --v) head = new Node{v, head}; head = reverse_in_groups(head, 4); for (const Node* p = head; p != nullptr; p = p->next) { std::cout << p->value << (p->next ? " " : "\n"); } } ``

5 question(s) left on this page.