Embercode
✕
Stacks and QueuesQuick quiz

Stack and queue bug hunt

8 questions. Covers Debugging lab: stack and queue bugs.

Questions 1 to 5 of 8

  1. 1. A stack has three array slots, and its full test is written like this. ``cpp struct ArrayStack { static constexpr int capacity = 3; int data[capacity]{}; int size = 0; bool isFull() const { return size == capacity - 1; } bool push(int x) { if (isFull()) return false; data[size++] = x; return true; } }; `` Which statement describes the bug?
  2. 2. A stack keeps top, the index of the top item, and its empty test is top == 0. The main code pushes 7, pops it, and then loops while the stack is not empty. ``cpp struct TopStack { std::vector<int> data = std::vector<int>(3); int top = -1; bool isEmpty() const { return top == 0; } void push(int x) { data[++top] = x; } int pop() { return data[top--]; } }; // main TopStack s; s.push(7); std::cout << "pop " << s.pop() << '\n'; while (!s.isEmpty()) { std::cout << "pop " << s.pop() << '\n'; } `` What goes wrong when the loop runs?
  3. 3. The linked stack below is supposed to push a new node onto the top. Each node has a next pointer to the node under it. ``cpp void pushBroken(Node*& head, int x) { Node* n = new Node{x}; head = n; } `` Which change fixes the push?
  4. 4. A linked queue has head and tail. The dequeue below frees the front node, but it never changes tail. ``cpp bool dequeue(int& out) { if (head == nullptr) return false; Node* old = head; out = old->value; head = head->next; delete old; return true; } `` Which change fixes the bug?
  5. 5. What does this program print? ``cpp #include <iostream> struct Node { int value; Node* next = nullptr; }; void pushBroken(Node*& head, int x) { Node* n = new Node{x}; head = n; } bool pop(Node*& head, int& out) { if (head == nullptr) return false; out = head->value; Node* old = head; head = head->next; delete old; return true; } int main() { Node* head = nullptr; pushBroken(head, 5); pushBroken(head, 6); int v = 0; while (pop(head, v)) { std::cout << "pop " << v << '\n'; } std::cout << "stack is empty\n"; } `` Choose the output.

5 question(s) left on this page.