[LeetCode]--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 elem

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.
Notes:
You must use only standard operations of a stack – which means only push to top, peek/pop from top, size, and is empty operations are valid.
Depending on your language, stack may not be supported natively. You may simulate a stack by using a list or deque (double-ended queue), as long as you use only standard operations of a stack.
You may assume that all operations are valid (for example, no pop or peek operations will be called on an empty queue).

跟前面用队列实现堆原理是差不多的。

class MyQueue {

        Stack<Integer> s1 = new Stack<Integer>();
        Stack<Integer> s2 = new Stack<Integer>();

        // Push element x to the back of queue.
        public void push(int x) {
            s1.push(x);
        }

        // Removes the element from in front of queue.
        public void pop() {
            while (s1.size() > 1)
                s2.push(s1.pop());
            s1.pop();
            while (s2.size() > 0)
                s1.push(s2.pop());
        }

        // Get the front element.
        public int peek() {
            while (s1.size() > 0)
                s2.push(s1.pop());
            int n = s2.peek();
            while (s2.size() > 0)
                s1.push(s2.pop());
            return n;
        }

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

LeetCode官方链接

目录
相关文章
|
存储
LeetCode 232. Implement Queue using Stacks
使用栈实现队列的下列操作: push(x) -- 将一个元素放入队列的尾部。 pop() -- 从队列首部移除元素。 peek() -- 返回队列首部的元素。 empty() -- 返回队列是否为空。
59 0
LeetCode 232. Implement Queue using Stacks
LeetCode 225. Implement Stack using Queues
使用队列实现栈的下列操作: push(x) -- 元素 x 入栈; pop() -- 移除栈顶元素; top() -- 获取栈顶元素; empty() -- 返回栈是否为空
60 0
LeetCode 225. Implement Stack using Queues
LeetCode 225:用队列实现栈 Implement Stack using Queues
题目: 使用队列实现栈的下列操作: push(x) -- 元素 x 入栈 pop() -- 移除栈顶元素 top() -- 获取栈顶元素 empty() -- 返回栈是否为空 Implement the following operations of a stack using queues.
1047 0
LeetCode 232:用栈实现队列 Implement Queue using Stacks
题目: 使用栈实现队列的下列操作: push(x) -- 将一个元素放入队列的尾部。 pop() -- 从队列首部移除元素。 peek() -- 返回队列首部的元素。 empty() -- 返回队列是否为空。
648 0
|
算法 Java C语言
LeetCode 28:实现strStr() Implement strStr()
公众号:爱写bug(ID:icodebugs) 作者:爱写bug 实现 strStr() 函数。 给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。
679 0