232:用栈实现队列

LeetCode 用栈实现队列:使用栈实现队列的下列操作:

push(x) -- 将一个元素放入队列的尾部。

pop() -- 从队列首部移除元素。

peek() -- 返回队列首部的元素。

empty() -- 返回队列是否为空。

思路:双栈实现。从 in 栈入数据,从 out 栈出数据,当需要获取队首元素或者移除队首元素时,先判断 out 栈是否为空,如果不为空,直接操作。如果为空,需要先将 in 栈的数据一个一个移入 out 栈,这样数据在 out 栈中就是期待的样子。

 

 

import java.util.Stack;
/*E push(E item) 压栈
E pop()        出栈
E peek()        查看栈顶元素
boolean empty() 判断栈是否为空 */
public class MyQueue {
    private Stack<Integer> in;
    private Stack<Integer> out;
    /** 初始化 */
    public MyQueue() {
        in = new Stack();
        out = new Stack();
    }
    /** 将一个元素放入队列的尾部 */
    public void push(int x) {
        in.push(x);
    }
    /** 从队列首部移除元素*/
    public int pop() {
        if(out.isEmpty()){
            while(in.size() != 0){
                int tmp = in.pop();
                out.push(tmp);
            }
        }
        return out.pop();
    }
    /** 返回队列首部的元素*/
    public int peek() {
        if(out.isEmpty()){
            while(in.size() != 0){
                int tmp = in.pop();
                out.push(tmp);
            }
        }
        int v = out.pop();
        out.push(v);
        return v;
    }

    /**返回队列是否为空*/
    public boolean empty() {
        return in.isEmpty() && out.isEmpty();
    }
    public static void main(String[] args) {
        MyQueue queue = new MyQueue();
        queue.push(1);
        queue.push(2);
        System.out.println(queue.peek());   // 返回 1
        System.out.println(queue.pop() );  // 返回 1
        System.out.println(queue.empty()); // 返回 false

    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值