剑指Offer打卡day6——AcWing 20. 用两个栈实现队列

【题目描述】
在这里插入图片描述

AcWing 20. 用两个栈实现队列

【思路】
根据两种数据结构的特点,队列:先进先出 。栈:先进后出。
因此想到使用两个栈,一个作为数据栈,另一个用于中转。当进行队列的peek和pop操作时,只要通过中转栈使得原先数据栈中的栈底元素变为中转栈的栈顶元素,就使得中转栈的peek、pop操作与队列一致。

class MyQueue {
    /*
    思路是当进行队列的peek和pop操作时,要使得原先数据栈中的栈底元素变为栈顶元素
    */
    Stack<Integer> stack = new Stack<Integer>();  //数据栈
    Stack<Integer> stack2 = new Stack<Integer>(); //中转栈 做弹出 和取栈顶用
    /** Initialize your data structure here. */
    public MyQueue() {

    }
   
    /** Push element x to the back of queue. */
    public void push(int x) {
        stack.push(x);
    }
    
    /** Removes the element from in front of queue and returns that element. */
    //题目说了:在队列为空时,不会进行pop或者peek等操作;
    public int pop() {
        //将stack中的元素自栈顶push到stack2中
        while( !stack.empty() ){
            //将stack的栈顶元素移动到stack2栈底 相当于移动到队尾
            stack2.push( stack.pop() );
        }
        int value = stack2.pop();
        //再将剩余元素重新push回stack
        while( !stack2.empty()){
            stack.push( stack2.pop());
        }
        return value;
    }
    
    /** Get the front element. */
    public int peek() {
         //将stack中的元素push到stack2中
        while( !stack.empty() ){
            //将stack的栈顶元素移动到stack2栈底 相当于队尾
            stack2.push( stack.pop() );
        }
        int value = stack2.peek();
        //再将剩余元素重新push会stack
        while( !stack2.empty()){
            stack.push( stack2.pop());
        }
        return value;
        
    }
    
    /** Returns whether the queue is empty. */
    public boolean empty() {
        return stack.empty();
    }
}

/**
 * Your MyQueue object will be instantiated and called as such:
 * MyQueue obj = new MyQueue();
 * obj.push(x);
 * int param_2 = obj.pop();
 * int param_3 = obj.peek();
 * boolean param_4 = obj.empty();
 */
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值