Implement Queue using Stacks leetcode

来源:互联网 发布:airpak软件下载 编辑:程序博客网 时间:2024/05/29 17:56
This is really a classic problem, no more word need for this.
class MyQueue {Stack<Integer> stack1 = new Stack<Integer>();Stack<Integer> stack2 = new Stack<Integer>();    // Push element x to the back of queue.    public void push(int x) {        stack1.push(x);    }    // Removes the element from in front of queue.    public void pop() {        if(stack2.empty())        {        while(!stack1.empty())        {        int temp = stack1.pop();        stack2.push(temp);        }        }        stack2.pop();    }    // Get the front element.    public int peek() {         if(stack2.empty())        {        while(!stack1.empty())        {        int temp = stack1.pop();        stack2.push(temp);        }        }        int ans = stack2.pop();        stack2.push(ans);        return ans;    }    // Return whether the queue is empty.    public boolean empty() {    if(stack1.empty()&&stack2.empty())    return true;    else    return false;            }}

0 0