首页 > 其他 > 详细

232. 用栈实现队列 + 栈 + 队列

时间:2021-03-07 22:13:59      阅读:32      评论:0      收藏:0      [点我收藏+]

232. 用栈实现队列

LeetCode_232

题目描述

技术分享图片

方法一:在push时将原有栈的元素全部出栈然后再将当前元如入栈,最后再将第二个栈的元素入第一个栈

class MyQueue{
    int num;
    Deque<Integer> sta1, sta2;//使用双端队列来模拟栈
    /** Initialize your data structure here. */
    public MyQueue() {
        sta1 = new LinkedList<>();
        sta2 = new LinkedList<>();
    }
    
    /** Push element x to the back of queue. */
    public void push(int x) {
        while(!sta1.isEmpty()){
            sta2.push(sta1.pop());
        }
        sta1.push(x);
        while(!sta2.isEmpty()){
            sta1.push(sta2.pop());
        }
    }
    
    /** Removes the element from in front of queue and returns that element. */
    public int pop() {
        return sta1.pop();
    }
    
    /** Get the front element. */
    public int peek() {
        return sta1.peek();
    }
    
    /** Returns whether the queue is empty. */
    public boolean empty() {
        return sta1.isEmpty();
    }
}

/**
 * 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();
 */

方法二:两个栈分为入栈和出栈

  1. 在peek或者push的时候,且此时出栈为空,则需要将入栈的所有元素进入出栈中
  2. 在push时只需要将元素进入入栈即可,起到了暂存元素的作用。
class MyQueue{
    int num;
    Deque<Integer> insta, outsta;//使用双端队列来模拟栈
    /** Initialize your data structure here. */
    public MyQueue() {
        insta = new LinkedList<>();
        outsta = new LinkedList<>();
    }
    
    /** Push element x to the back of queue. */
    public void push(int x) {
        insta.push(x);
    }
    
    /** Removes the element from in front of queue and returns that element. */
    public int pop() {
        if(outsta.isEmpty()){
            while(!insta.isEmpty()){
                 outsta.push(insta.pop());
            }
        }
        
        return outsta.pop();
    }
    
    /** Get the front element. */
    public int peek() {
        if(outsta.isEmpty()){
            while(!insta.isEmpty()){
                 outsta.push(insta.pop());
            }
        }
        return outsta.peek();
    }
    
    /** Returns whether the queue is empty. */
    public boolean empty() {
        return outsta.isEmpty() && insta.isEmpty();
    }
}

/**
 * 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();
 */

232. 用栈实现队列 + 栈 + 队列

原文:https://www.cnblogs.com/GarrettWale/p/14496322.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!