Search code examples
javalinked-listqueue

Trying to reverse a queue in Java


I'm trying to reverse a queue using recursion. I have already implemented the process using queue and a stack, but I would like to learn the recursive way also.

The following is a code from this website

import java.io.*;
import java.util.*;
class GFG {

// Utility function to print the queue
public static void Print(Queue<Integer> Queue)
{
    while (Queue.size() > 0) {
    System.out.print(Queue.peek() + " ");
    Queue.remove();
    }
}

// Function to reverse the queue
public static void reverseQueue(Queue<Integer> q)
{
    // base case
    if (q.size() == 0)
    return;
    // storing front(first element) of queue
    int fr = q.peek();

    // removing front
    q.remove();

    // asking recursion to reverse the
    // leftover queue
    reverseQueue(q);

    // placing first element
    // at its correct position
    q.add(fr);
}

public static void main(String[] args)
{
    Queue<Integer> Queue = new LinkedList<>();

    Queue.add(10);
    Queue.add(20);
    Queue.add(30);
    Queue.add(40);
    Queue.add(50);
    Queue.add(60);
    Queue.add(70);
    Queue.add(80);
    Queue.add(90);
    Queue.add(100);

    reverseQueue(Queue);
    Print(Queue);
}
}

Now my doubt exist on the reverseQueue() method, the front value is stored in a variable fr using peek().Now my doubt is that how does this function reverse the queue? The value of fr changes each time. The last value of fr contains lets say 40 from the queue(10,20,30,40). How are the values 30,20 and 10 stored ?


Solution

  • How are the values 30,20 and 10 stored ?

    This question seems to suggest you think there is only one fr variable. This is not true. fr is a local variable that exists during the execution of reverseQueue. And as you have several executions of reverseQueue, you have as many fr variables, and each has a different value. Once a recursive call finishes and the current execution of reverseQueue can continue, it will have access to its own fr variable which was not affected by any of the deeper recursive calls.

    I hope that clarifies your doubt.

    On another subject: your Print function removes all elements from the given queue. This is odd: no-one would expect that after printing a queue it ends up empty.