用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。

栈的特性是先进后出,队列的特性是先进先出。

对于队列push的操作:直接入栈stack1。

对于队列pop的操作:将stack作为存储栈,将stack2作为临时缓冲栈

先将元素入stack1(stack.push),再将stack1中元素出栈,入stack2栈,当stack1中为空时,弹出stack2中最上面的元素,即出列。

方法一:

package demo4;
import java.util.Stack;

public class Solution {
    Stack<Integer> stack1 = new Stack<Integer>();
    Stack<Integer> stack2 = new Stack<Integer>();

    public void push(int node) {
        stack1.push(node);
    }
    public void pop() {
        while (!stack1.isEmpty()) {
            stack2.push(stack1.pop());}
        while (!stack2.isEmpty())
            System.out.println(stack2.pop());
        }
    public static void main(String args[]){
        Solution newStack=new Solution();
        newStack.push(1);
        newStack.push(2);
        newStack.push(3);
        newStack.push(4);
        newStack.pop();
    }
}

若要求pop()方法必须有返回值,则使用下面这个方法

方法二:

package demo4;
import java.util.Stack;

public class Solution {
    Stack<Integer> stack1 = new Stack<Integer>();
    Stack<Integer> stack2 = new Stack<Integer>();

    public void push(int node) {
        stack1.push(node);
    }

    public int pop() {
        if(stack2.isEmpty()){
            while (!stack1.isEmpty()) {
                stack2.push(stack1.pop());
            }
        }
        return stack2.pop();
    }



    public static void main(String args[]){
        Solution newStack=new Solution();
        newStack.push(1);
        newStack.push(2);
        newStack.push(3);
        newStack.push(4);
        while (newStack!=null){
            System.out.println(newStack.pop());
        }

    }
}

结果抛出异常

用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。

考虑到java抛出异常

用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。

做以下代码修改

package demo4;
import java.util.Stack;

public class Solution {
    Stack<Integer> stack1 = new Stack<Integer>();
    Stack<Integer> stack2 = new Stack<Integer>();

    public void push(int node) {
        stack1.push(node);
    }

    public int pop() {
        if(stack2.isEmpty()){
            while (!stack1.isEmpty()) {
                stack2.push(stack1.pop());
            }
        }
        return stack2.pop();
    }
    public boolean isEmpty(){
        return stack2.isEmpty()&&stack1.isEmpty();
    }



    public static void main(String args[]){
        Solution newStack=new Solution();
        newStack.push(1);
        newStack.push(2);
        newStack.push(3);
        newStack.push(4);
        while (!newStack.isEmpty()){
            System.out.println(newStack.pop());
        }

    }
}

运行成功!

用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。