简体   繁体   中英

Why does the pop method in my code for stacks does not execute?

I am trying to make a simple code for Stacks using two Queues. I understand the concept, and I have tried the following code to implement this.

import java.util.LinkedList;
import java.util.Queue;

public class StackWithQueues {

Queue<Integer> q1 = new LinkedList<Integer>();
Queue<Integer> q2 = new LinkedList<Integer>();
int size;

public StackWithQueues() {

    this.size = 0;

}

public void push(int ele) {

    q1.add(ele);
    size++;

    System.out.println("Pushed "+ele);
}

public void pop() {

    while(!q1.isEmpty()) {

        q2.add(q1.peek());
        q2.poll(); 

    }

    int popped = q2.peek();

    size--;
    q1 = q2;

    System.out.println("Popped "+popped);

}

public static void main(String[] args) {

    StackWithQueues s = new StackWithQueues();

    for(int i=0;i<5;i++)
        s.push(i+1);

    s.pop();
    s.pop();
    s.pop();


}

}

I can't understand why the pop() method is not doing anything. The console shows the following output on execution.

Pushed 1
Pushed 2
Pushed 3
Pushed 4
Pushed 5

I would appreciate if someone can explain what is going wrong with the pop method here.

Your pop method has an infinite loop. It keeps adding elements to q2 without removing anything from q1 (since q1.peek() doesn't remove the head of the queue), so q1 will never become empty.

Something like this seems to work:

public void pop() {
    int popped = 0;
    while(!q1.isEmpty()) {

      popped = q1.poll ();
      if (!q1.isEmpty ()) {
        q2.add (popped);
      }
    }

    size--;
    Queue<Integer> temp = q1;
    q1 = q2;
    q2 = temp;

    System.out.println("Popped "+popped);
}

Note that it still lacks a test for empty stack.

You had several issues:

  1. This is a stack, so pop should return the last element pushed, not the first.
  2. In the first pop you set q1 = q2 , and from this point on you only have 1 queue. You should create a new empty queue for q2 (or assign to it the original q1).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM