Implement Stack using Queues leetcode
2016-01-15 22:23
609 查看
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.
不用多想,可以使用两个queue来实现,代码如下
耗时在pop上
查看其它人的代码,发现居然可以使用一个queue来实现,实现思路非常巧妙,每一次push操作都将queue之前的元素都移到后面,使其保持栈的排序
如:
push 1
1
push 2
2 1
push 3
3 2 1
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.
不用多想,可以使用两个queue来实现,代码如下
耗时在pop上
class Stack { public: // Push element x onto stack. void push(int x) { que1.push(x); } // Removes the element on top of the stack. void pop() { while (que1.size() > 1) { que2.push(que1.front()); que1.pop(); } que1.pop(); while (!que2.empty()) { que1.push(que2.front()); que2.pop(); } } // Get the top element. int top() { return que1.back(); } // Return whether the stack is empty. bool empty() { return que1.empty(); } private: queue<int> que1; queue<int> que2; };
查看其它人的代码,发现居然可以使用一个queue来实现,实现思路非常巧妙,每一次push操作都将queue之前的元素都移到后面,使其保持栈的排序
如:
push 1
1
push 2
2 1
push 3
3 2 1
class Stack { public: queue<int> que; // Push element x onto stack. void push(int x) { que.push(x); for (int i = 0; i<que.size() - 1; ++i) { que.push(que.front()); que.pop(); } } // Removes the element on top of the stack. void pop() { que.pop(); } // Get the top element. int top() { return que.front(); } // Return whether the stack is empty. bool empty() { return que.empty(); } };
相关文章推荐
- UI_2
- UI_1
- UI_视图界面
- String、StringBuffer和StringBuilder的区别
- 自定义视图与工厂模式
- IOS动画中的枚举UIViewAnimationOptions
- Android界面设计的4种方式之二——在Java代码中控制UI界面
- 【leetcode】100. Same Tree My Submissions Question
- query specified join fetching, but the owner of the fetched association was not present in the select list
- Android开发出现Warning:Gradle version 2.10 is required. Current version is 2.8. If u
- 【Codeforces 570D 】Tree Requests dfs序+二分
- iOS 【关于几个常用UIColor宏定义】
- Animation动画详解(四)——ValueAnimator基本使用
- 【UEditor】百度UE富文本自定义按钮添加文本
- Android UI之ImageSwitcher && TextSwitcher 实现图文翻页
- Django+Query
- Dissecting Message Queues(不同消息中间件Throughput和latency
- Java对象的强、软、弱和虚引用原理+结合ReferenceQueue对象构造Java对象的高速缓存器
- easyui 自定义验证,动态设置提示信息
- EasyUI 1.3.6 DateBox添加清空按钮