栈-E232-用栈实现队列

2019-03-20  本文已影响0人  三次元蚂蚁

题目

  1. push(x):将x放入队尾
  2. pop():将队首元素移除并返回该元素
  3. peek():返回队首元素
  4. empty():队列为空返回true,反之false

只允许使用栈的标准操作:push(x), pop(),peek(),empty(),size()

假设所给出的操作都是合理的

思路

  1. 执行push(x)操作前队列为空时
  2. 执行pop()操作中将得到的元素返回时
  3. 执行pop()操作中将另一个栈栈顶元素pop()后存储此时另一个栈的栈顶元素

特别注意:存储队首元素的元素类型应为包装类型,否则可能导致null类型拆箱时报空指针异常

代码

class MyQueue {
    private Integer mTopValue; //must be Integer avoid unboxing leading to NullException
    private LinkedList<Integer> mStack = new LinkedList<>();
    private LinkedList<Integer> mTempStack = new LinkedList<>();

    /** Initialize your data structure here. */
    public MyQueue() {
        
    }
    
    /** Push element x to the back of queue. */
    public void push(int x) {
        if (mStack.isEmpty()) {
            mTopValue = x;
        }
        mStack.push(x);
    }
    
    /** Removes the element from in front of queue and returns that element. */
    public int pop() {
        while (!mStack.isEmpty()) {
            mTempStack.push(mStack.pop());
        }
        int temp = mTempStack.pop();
        mTopValue = mTempStack.peek(); //must store after pop
        while (!mTempStack.isEmpty()) {
            mStack.push(mTempStack.pop());
        }
        return temp;
    }
    
    /** Get the front element. */
    public int peek() {
        return mTopValue;
    }
    
    /** Returns whether the queue is empty. */
    public boolean empty() {
        return mStack.isEmpty();
    }
}
上一篇 下一篇

猜你喜欢

热点阅读