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

10 篇文章 0 订阅

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

对于队列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());
        }

    }
}

结果抛出异常

考虑到java抛出异常

做以下代码修改

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());
        }

    }
}

运行成功!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值