#40 Implement Queue by Two Stacks
来源:互联网 发布:可以拼长图的软件 编辑:程序博客网 时间:2024/05/16 00:44
题目描述:
As the title described, you should only use two stacks to implement a queue's actions.
The queue should support push(element)
, pop()
and top()
where pop is pop the first(a.k.a front) element in the queue.
Both pop and top methods should return the value of first element.
Example
push(1)pop() // return 1push(2)push(3)top() // return 2pop() // return 2
Challenge
Mycode(AC = 37ms):implement it by two stacks, do not use any other data structure and push, pop and top should be O(1) by AVERAGE.
class Queue {public: stack<int> stack1; stack<int> stack2; Queue() { // do intialization if necessary } void push(int element) { // write your code here stack1.push(element); } int pop() { // write your code here while (!stack1.empty()) { stack2.push(stack1.top()); stack1.pop(); } int val = stack2.top(); stack2.pop(); while(!stack2.empty()) { stack1.push(stack2.top()); stack2.pop(); } return val; } int top() { // write your code here while (!stack1.empty()) { stack2.push(stack1.top()); stack1.pop(); } int val = stack2.top(); while(!stack2.empty()) { stack1.push(stack2.top()); stack2.pop(); } return val; }};
0 0
- #40 Implement Queue by Two Stacks
- Lintcode 40:Implement Queue by Two Stacks
- implement-queue-by-two-stacks
- Implement Queue by Two Stacks
- Implement Queue by Two Stacks
- Implement Queue by Two Stacks
- Implement Queue by Two Stacks
- implement a queue by using two stacks
- [刷题]Implement Queue by Two Stacks
- lintcode: Implement Queue by Two Stacks
- [Lintcode]Implement Queue by Two Stacks
- Implement Queue by Two Stacks 解题报告
- implement a queue by using two stacks [No. 31]
- Lintcode40 Implement Queue by Two Stacks solution 题解
- 【LeetCode】 Implement Queue by Two Stacks用栈实现队列
- Implement Queue with Two Stacks
- Implement Queue with two Stacks Java
- 40.Implement Queue by Two Stacks-用栈实现队列(中等题)
- android机顶盒简单案例
- [leetcode] 207. Course Schedule
- android wifi连接 有无密码均实机验证成功案例
- 使用Scrapy对新闻进行爬虫(一)
- #39 Recover Rotated Sorted Array
- #40 Implement Queue by Two Stacks
- 用抛物线的点实现HTC Vive瞬移系统
- 使用Scrapy对新闻进行爬虫(二)
- MAC PRO java环境搭建
- 96. Unique Binary Search Trees
- [google interview] 输出所有的整数
- 转载:理解LINUX的MEMORY OVERCOMMIT
- 占位
- 占位