232. Implement Queue using Stacks

Implement the following operations of a queue using stacks.

push(x) -- Push element x to the back of queue.
pop() -- Removes the element from in front of queue.
peek() -- Get the front element.
empty() -- Return whether the queue is empty.

分析:用两个Stack实现queue,这里我们在pop和peek操作是都需要更新Stack2来保证Stack2非空的。另外Stack2应该在为empty后再填充,才能保证原有的位置没有发生改变。
例如:push1 push2 ,pop1 后 stack2 应该还留下了2,此时进行push3 push4 后我们不应该将3,4push到stack2中,因为stack2中还不是空的 。如果push的话会导致 顺序变成了2,4,3.在pop就不对了。

class MyQueue {
        Stack<Integer> stack1 = new Stack<>();
         Stack<Integer> stack2 = new Stack<>(); 
    /** Initialize your data structure here. */
    public MyQueue() {
        
    }
    
    /** Push element x to the back of queue. */
    public void push(int x) {
        stack1.push(x);
    }
    
    /** Removes the element from in front of queue and returns that element. */
    public int pop() {
       if(stack2.empty())
        {
            while(!stack1.empty())
            stack2.push(stack1.pop());
        }
        return stack2.pop();
    }
    
    /** Get the front element. */
    public int peek() {
        if(stack2.empty())
        {
            while(!stack1.empty())
            stack2.push(stack1.pop());
        }
        return stack2.peek();
    }
    
    /** Returns whether the queue is empty. */
    public boolean empty() {
        return stack1.empty()&&stack2.empty();
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容