Implement Queue using Stacks
class MyQueue {
    // Using two stacks.
    Stack<Integer> s1 = new Stack<Integer>();// Pop out.
    Stack<Integer> s2 = new Stack<Integer>();// Cache.
    
    // Push element x to the back of queue.
    public void push(int x) {
        s2.push(x);
    }

    // Removes the element from in front of queue.
    public void pop() {
        if (empty()) {
            return;
        }
        if (s1.isEmpty()) {
            while (!s2.isEmpty()) {
                s1.push(s2.peek());
                s2.pop();
            }
        }
        s1.pop();
    }

    // Get the front element.
    public int peek() {
        if (empty()) {
            return -1;
        }
        if (s1.isEmpty()) {
            while (!s2.isEmpty()) {
                s1.push(s2.peek());
                s2.pop();
            }
        }
        return s1.peek();
    }

    // Return whether the queue is empty.
    public boolean empty() {
        return s1.isEmpty() && s2.isEmpty();
    }
}

阅读更多
文章标签: Stack Data Structure
个人分类: Leetcode 刷题
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

不良信息举报

Implement Queue using Stacks

最多只允许输入30个字

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭