您的位置:首页 > 产品设计 > UI/UE

leetcode 225 & 232.Implement Stack using Queues & Implement Queue using Stacks

2017-09-09 11:27 411 查看
突然听人说起有同学做了某游戏公司的笔试题,遇到如何用栈实现队列,想起来自己在半年前做过用队列实现栈和用栈实现队列,现在回忆起来,只记得如果用栈实现队列,忘了用队列实现栈了,在此记录一下。

总所周知,栈是先进先出,队列是先进后出。

对于一个序列来说,一个序列进入队列之后,再出来,序列顺序不变。

在进入栈之后,再出来,序列顺序相反了。

无论是用栈实现队列,还是用队列实现栈,实际上考虑的都是如何将这个序列弄反

从此思路出发,对于一个队列来说,如果将序列弄反,当然是在每次插入数字的时候,都把整个队列放在新插入数字的后面,这一点用队列是很方便实现的。当然,这样每次push操作的复杂度都在O(n),是很浪费时间的,这个思路的循环相当于又利用一个队列的资源

下面是代码:

class MyStack {
public:
/** Initialize your data structure here. */
queue<int> que;
MyStack() {

}

/** Push element x onto stack. */
void push(int x) {
que.push(x);
for(int i=1;i<que.size();++i)
{
que.push(que.front());
que.pop();
}
}

/** Removes the element on top of the stack and returns that element. */
int pop() {
int result=que.front();
que.pop();
return result;
}

/** Get the top element. */
int top() {
return que.front();
}

/** Returns whether the stack is empty. */
bool empty() {
return que.empty();
}
};

/**
* 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();
*/


至于如何用栈实现队列,可以用两个栈来实现两次序列反转,在这边就不贴代码了,难度也不大。

4000
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: