Implement Queue using Stacks

原创 2015年07月09日 14:37:39
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();
    }
}

相关文章推荐

【leetcode】232. Implement Queue using Stacks

一、题目描述 Implement the following operations of a queue using stacks. push(x) -- Push element x...

LeetCode:Implement Queue using Stacks

LeetCode:Implement Queue using Stacks1、题目: Implement the following operations of a queue using stac...
  • BestZem
  • BestZem
  • 2016年07月16日 22:08
  • 159

LeetCode232 Implement Queue using Stacks Java 题解

题目: Implement the following operations of a queue using stacks. push(x) -- Push element x to...

232. Implement Queue using Stacks(C语言版本)(Time Limit Exceeded)

Implement the following operations of a queue using stacks. push(x) -- Push element x to the back...

LeetCode232—Implement Queue using Stacks

LeetCode232: Implement Queue using Stacks

LeetCode Implement Queue using Stacks

题目: Implement the following operations of a queue using stacks. push(x) -- Push element x to...

232. Implement Queue using Stacks

leetcode 232 - Easy - 剑指offer题目7

LeetCode 232 Implement Queue using Stacks(用栈来实现队列)(*)

翻译用栈来实现队列的下列操作。push(x) —— 将元素x写入到队列的尾部 pop() —— 从队列首部移除元素 peek() —— 返回队列首部元素 empty() —— 返回队列是否为空注意:你...
  • NoMasp
  • NoMasp
  • 2016年01月20日 21:18
  • 2422

[leetcode] Implement Queue using Stacks

题目链接在此。 Implement the following operations of a queue using stacks. push(x) -- Push element x t...

[leetcode: Python]232. Implement Queue using Stacks

题目: Implement the following operations of a queue using stacks.push(x) – Push element x to the back...
  • NXHYD
  • NXHYD
  • 2017年05月12日 13:09
  • 139
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:Implement Queue using Stacks
举报原因:
原因补充:

(最多只允许输入30个字)