用队列实现栈
来源:互联网 发布:什么是java注解 编辑:程序博客网 时间:2024/05/14 12:15
关于面试中是否应该考算法,众说纷纭,我不站队,美其名曰理性看待,哈哈。说重要的可能他们工作中需要使用大量的算法知识,说不重要的可能他们项目中没有用到什么算法知识,并且用到也已经有现成的库替他们解决了这些算法问题,还没有到需要去优化轮子的地步。如果我是面试官,我只会考最基本的算法概念,更看重一些计算机理论知识、视野、做一件事是否明白主次之分,这些构成个人的整体素质。
用队列实现一个栈,这个题目见过很多次了,但我从没有去实现它的冲动,因我的工作中没有碰到类似的问题,我压根不知道什么时候需要这样去折腾,等到需要的时候再去折腾也还可以,时间精力有限,不可能什么都能提前研究透了。要是说这种题目可以锻炼思维,好吧,那我就锻炼一下,写几行简单的代码来实现这个基于队列的栈。我不知道别人是怎么实现的,有空再看看,我的实现如下,经测试没啥问题:
class Stack {
public:
Stack()
{
qnum = 1;
}
// Push element x onto stack.
void push(int x) {
if(q1.empty())
{
q1.push(x);
qnum = 1;
}
else if(q2.empty())
{
q2.push(x);
qnum = 2;
}
else if(qnum == 1)
{
while(!q2.empty())
{
q1.push(q2.front());
q2.pop();
}
q2.push(x);
qnum = 2;
}
else if(qnum == 2)
{
while(!q1.empty())
{
q2.push(q1.front());
q1.pop();
}
q1.push(x);
qnum = 1;
}
}
// Removes the element on top of the stack.
void pop() {
if(qnum == 1)
{
if(!q1.empty()) q1.pop();
if(q1.empty()) qnum = 2;
}
else if(qnum == 2)
{
if(!q2.empty()) q2.pop();
if(q2.empty()) qnum = 1;
}
}
// Get the top element.
int top() {
if(qnum == 1)
{
if(!q1.empty()) return q1.front();
}
else if(qnum == 2)
{
if(!q2.empty()) return q2.front();
}
}
// Return whether the stack is empty.
bool empty() {
return q1.empty() && q2.empty();
}
private:
queue<int> q1;
queue<int> q2;
int qnum;
};
- 用栈实现队列
- 用队列实现栈
- 用栈实现队列
- 用队列实现栈
- 用栈实现队列
- 用栈实现队列
- 用栈实现队列-用队列实现栈
- 用两个栈实现队列 & 用两个队列实现栈
- 用栈实现队列-用队列实现栈
- java:用栈实现队列+用队列实现栈
- 用两个队列实现栈&用两个栈实现队列
- 用两个栈实现队列 & 两个队列实现一个栈
- 两个栈实现队列&&用两个队列实现一个栈
- 用两个栈实现队列 & 两个队列实现栈
- 用双队列实现栈和用双栈实现队列
- 用两个栈实现队列
- 用两个栈实现队列
- 用两个栈实现队列
- an internal error occurred during building workspace
- zoj 1204 Additive equations
- HDU 5305 Friends (DFS)
- 1008. Elevator (20)
- linux awk命令详解
- 用队列实现栈
- 二分法查找(Binary Search)
- 关于jsp的include
- 最长严格上升子序列
- 小白学开发(iOS)OC_类方法和对象方法(2015-07-22)
- apache无法解析php解决方法
- Linux kernel 分析之二十一:定时器-巧妙的定时器算法
- 在oc中遍历字符串的至少可以使用以下两种方法
- linux基本命令学习笔记