public static void reverseFirstK(Queue<Integer> q, int k) {
LinkedList<Integer> stack = new LinkedList<>();
for (int i = 0; i < k; i++) {
stack.push(q.remove());
}
System.out.println(q);
System.out.println(stack);
while (!stack.isEmpty()) {
q.add(stack.pop());
}
System.out.println(q);
for (int i = 0; i < q.size() - k; i++) {
q.add(q.remove());
}
System.out.println(q);
}
}
I was asked to write a program that given a value k and a queue of elements reverses the order of the first k elements of the queue, leaving the other elements in the same relative order. Through trial and error I arrived at the right code, although I don't get why it works.
For the sake of lucidity let the original queue be [10, 20, 30, 40, 50, 60, 70, 80, 90]. After the first for loop queue = [50, 60, 70, 80, 90] and stack = [40, 30, 20, 10]. Why is stack =/= [10,20,30,40]? My thought process was remove() removes the first element of the queue, and that push added elements to the end of a stack. So the steps would look something like
- queue = [20, 30, 40, 50, 60, 70, 80, 90],
stack = [10]
- queue = [30, 40, 50, 60, 70, 80, 90]
stack = [10, 20]
- queue = [40, 50, 60, 70, 80, 90] stack = [10, 20, 30]
etc.
Then after the while loop, the queue is [50, 60, 70, 80, 90, 40, 30, 20, 10]. What I don't understand here is why is the queue not [50, 60, 70, 80, 90, 10, 20, 30, 40] here? My thought process was that pop() removes elements from the end of the stack, and add adds elements to the end of a queue. So the steps would look something like
Stack: [50, 60, 70, 80, 90] Queue: [40, 30, 20, 10]
Stack: [50, 60, 70, 80, 90, 10] Queue: [40, 30, 20]
Stack: [50, 60, 70, 80, 90, 10, 20] Queue: [40, 30] etc.
I would really appreciate some clarification on this.