leetcode 232. Implement Queue using Stacks 双栈实现队列

来源:互联网 发布:mui.pulltorefresh.js 编辑:程序博客网 时间:2024/06/06 13:48

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.
Notes:
You must use only standard operations of a stack – which means only push to top, peek/pop from top, size, and is empty operations are valid.
Depending on your language, stack may not be supported natively. You may simulate a stack by using a list or deque (double-ended queue), as long as you use only standard operations of a stack.
You may assume that all operations are valid (for example, no pop or peek operations will be called on an empty queue).

这道题是也是一个经典的问题,就是考察双栈实现一个队列。

建议和这一道题一起学习leetcode 225. Implement Stack using Queues 双队列实现栈

两个栈实现堆是经典算法。
进队时,压入stk1。
出队时,stk2弹出。
stk2为空时,stk1倒入stk2。两次逆序恢复了原序。

代码如下:

import java.util.Stack;/* *  * 两个栈实现堆是经典算法。 * 进队时,压入stk1。 * 出队时,stk2弹出。 * stk2为空时,stk1倒入stk2。两次逆序恢复了原序。 * */public class MyQueue {    Stack<Integer> stack1=null;    Stack<Integer> stack2=null;    /** Initialize your data structure here. */    public MyQueue()     {        stack1=new Stack<>();        stack2=new Stack<>();    }    /** 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()==false)                stack2.push(stack1.pop());        }        return stack2.pop();    }    /** Get the front element. */    public int peek()     {        if(stack2.empty())        {            while(stack1.empty()==false)                stack2.push(stack1.pop());        }        return stack2.peek();    }    /** Returns whether the queue is empty. */    public boolean empty()     {        return stack1.empty() && stack2.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
原创粉丝点击