232. Implement Queue using Stacks
来源:互联网 发布:windows 10 dpi 编辑:程序博客网 时间:2024/06/05 00:18
title
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).
solution
class Queue {public: // Push element x to the back of queue. void push(int x) { q1.push(x); } // Removes the element from in front of queue. void pop(void) { while(q1.size() > 1) { q2.push(q1.top()); q1.pop(); } if(q1.size() == 1) { q1.pop(); } while(!q2.empty()) { q1.push(q2.top()); q2.pop(); } } // Get the front element. int peek(void) { while(q1.size() > 1) { q2.push(q1.top()); q1.pop(); } if(q1.size() == 1) { x = q1.top(); } while(!q2.empty()) { q1.push(q2.top()); q2.pop(); } return x; } // Return whether the queue is empty. bool empty(void) { return q1.empty(); }private: stack <int> q1, q2; int x;};
run time: 0ms
2个stack
0 0
- 232. Implement Queue using Stacks
- 232. Implement Queue using Stacks
- 232. Implement Queue using Stacks
- 232. Implement Queue using Stacks
- 232. Implement Queue using Stacks
- 232. Implement Queue using Stacks
- 232. Implement Queue using Stacks
- 232. Implement Queue using Stacks
- 232. Implement Queue using Stacks
- 232. Implement Queue using Stacks
- 232. Implement Queue using Stacks
- 232. Implement Queue using Stacks
- 232. Implement Queue using Stacks
- 232. Implement Queue using Stacks
- 232. Implement Queue using Stacks
- 232. Implement Queue using Stacks
- 232. Implement Queue using Stacks
- 232. Implement Queue using Stacks
- 能够提高开发效率的Eclipse实用操作
- 深复制和浅复制(二)
- 三种JAVA常用实现字符串反转(Reverse)的方法
- HDU 1231 最大连续子序列
- CSS3基础入门学习: 背景制作实例!
- 232. Implement Queue using Stacks
- Android开发架构规范
- 有序数组,插入一个数后还保证有序
- Java enum的用法详解
- MAVEN 实践 探讨====一个真实的故事
- Java实现链式队列
- C++Operator
- NSString , NSArray和NSDictionary的遍历方式
- JVM实用参数(六) 吞吐量收集器