爱程序网

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.

 

代码如下:

class MyQueue {
    // Push element x to the back of queue.
    Stack<Integer>stack=new Stack<Integer>();
    public void push(int x) {
        if(stack.empty())
        stack.push(x);
        else{
            Stack<Integer> ss=new Stack<Integer>();
            while(!stack.empty())
            {
                ss.push(stack.peek());
                stack.pop();
            }
            stack.push(x);
             while(!ss.empty())
            {
                stack.push(ss.peek());
                ss.pop();
            }
           
        }
    }

    // Removes the element from in front of queue.
    public void pop() {
       stack.pop();
    }

    // Get the front element.
    public int peek() {
         return stack.peek();
    }

    // Return whether the queue is empty.
    public boolean empty() {
         return stack.empty();
    }
}

 

关于爱程序网 - 联系我们 - 广告服务 - 友情链接 - 网站地图 - 版权声明 - 人才招聘 - 帮助