ProgrammingHardAmazon OA · Goldman Sachs OA

What will be the output of the following pseudocode?

What will be the output of the following pseudocode?
// list: 1 -> 2 -> 3 -> 4 -> 5 -> NULL
Integer n = 5, k = 2
Node tail = last node
tail.next = head                    // make the list circular
Node p = head
for (each i from 1 to n - k - 1)
    p = p.next
end for
head = p.next
p.next = NULL
Print the values from head to NULL
  1. A. 3 4 5 1 2
  2. B. 5 4 3 2 1
  3. C. 2 3 4 5 1
  4. D. 4 5 1 2 3

Correct answer: D. 4 5 1 2 3

p stops at node 3 (n − k − 1 = 2 steps from node 1). The list is cut after it and the new head is node 4, giving a right rotation by k = 2: 4 5 1 2 3.

More Pseudocode and Code Tracing questions

Exams that ask this topic