关闭

Implement Queue using Stacks

标签: StackData Structure
180人阅读 评论(0) 收藏 举报
分类:
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();
    }
}

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:27543次
    • 积分:2361
    • 等级:
    • 排名:第16325名
    • 原创:214篇
    • 转载:2篇
    • 译文:0篇
    • 评论:0条