I am trying to understand the following method from here explained by Mahmood Akhtar. Please find the code snippet below:
public void push(int data) {
if (q1.peek() == null) {
q1.add(data);
} else {
for (int i = q1.size(); i > 0; i--) {
q2.add(q1.remove());
}
q1.add(data);
for (int j = q2.size(); j > 0; j--) {
q1.add(q2.remove());
}
}
}
Here is what I have understood :
Step 1: The first if statement checks whether queue q1 is null or not and if it's null, then a data is added.
Step 2: Otherwise, since q1 is full, we will have to move the data from q1 to q2. So, the first for loop in the else statement is basically starting from the size of the q1 and runs until the last element is encountered. All the elements are moved into q2. A new data is added into q1.
Step 3: Same process like Step 2 is repeated for q2.
Please correct me if my explanation is correct or not?
SECOND QUESTION:
In the pop method :
public int pop() {
if (q1.peek() == null) {
System.out.println("The stack is empty, nothing to return");
int i = 0;
return i;
} else {
int pop = q1.remove();
return pop;
}
}
How come they are deleting the first element from the queue q1? Because the first element in the queue q1 will be according to the FIFO principle and for stack it should be the last element?
What according to me should he be doing is that , he should be transferring all the elements into q2 from q1 until last element is left and then remove that element from the queue. Please correct me if I am wrong.
Thanks