原文链接 [每日 LeetCode] 225. Implement Stack using Queues
Description:
Implement the following operations of a stack using queues.
- push(x) -- Push element x onto stack.
- pop() -- Removes the element on top of the stack.
- top() -- Get the top element.
- empty() -- Return whether the stack is empty.
Example:
MyStack stack = new MyStack(); stack.push(1); stack.push(2); stack.top(); // returns 2 stack.pop(); // returns 2 stack.empty(); // returns false
Notes:
- You must use_only_standard operations of a queue -- which means only
push to back
,peek/pop from front
,size
, andis empty
operations are valid. - Depending on your language, queue may not be supported natively. You may simulate a queue by using a list or deque (double-ended queue), as long as you use only standard operations of a queue.
- You may assume that all operations are valid (for example, no pop or top operations will be called on an empty stack).
思路:本题是[每日 LeetCode] 232. Implement Queue using Stacks 镜像题,本题要求用队列结构实现队列的基本操作。由于队列先进先出的特性,考虑只使用一个队列完成操作,具体做法为:对每个栈的 push
操作后,对当前队列逆序,让队头始终保存刚刚压入的元素,如此一来即可实现栈的基本操作。
C++ 代码
class MyStack { public: /** Initialize your data structure here. */ MyStack() { } /** Push element x onto stack. */ void push(int x) { temp.push(x); for (int i=0; i<temp.size() - 1; i++){ temp.push(temp.front()); temp.pop(); } } /** Removes the element on top of the stack and returns that element. */ int pop() { int tem = temp.front(); temp.pop(); return tem; } /** Get the top element. */ int top() { return temp.front(); } /** Returns whether the stack is empty. */ bool empty() { return temp.empty(); } private: queue<int> temp; }; /** * Your MyStack object will be instantiated and called as such: * MyStack* obj = new MyStack(); * obj->push(x); * int param_2 = obj->pop(); * int param_3 = obj->top(); * bool param_4 = obj->empty(); */
运行时间:4ms
运行内存:8.9M
欢迎来到这里!
我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。
注册 关于