很常见的两道题:
1、用 queue 实现 stack:LeetCode - 225. Implement Stack using Queues
2、用 stack 实现 queue:LeetCode - 232. Implement Queue using Stacks
一、Implement Stack using Queues
就是用 queue 来模拟 stack,实现 push、top、pop、empty 功能(值得注意的是,STL 里的 pop 都是不返回值的,这里需要返回 top 值),题目保证不会有空的时候出现 top 或者 pop 的调用(STL 里的 queue 和 stack 在遇到这种情况时也只是运行时崩掉)。
1.1、用两个 queue 模拟 stack
用两个 queue 模拟,很容易理解,就是始终保持一个 queue 是空的,push 就往另一个 queue 里 push,然后 pop 的话就把不是空的 queue 一直往另一个原本是空的 queue 里边放,知道只剩一个元素,然后 pop 这个元素即可。代码很好写,也很常见,就不写了。
1.2、用一个 queue 模拟 stack
用一个 queue 的话,就是每次 push 一个数之后,把它前边的数,重新 pop 并 push 会 queue 中,这样每次新 push 的数就在 front 了,pop 和 top 就很方便了:
queue<int> q;
MyStack() {}
void push(int x) {
int cnt = q.size();
q.push(x);
while(cnt != 0) {
const int t = q.front();
q.pop();
q.push(t);
--cnt;
}
}
int pop() {
const int res = q.front();
q.pop();
return res;
}
int top() { return q.front(); }
bool empty() { return q.empty(); }
二、Implement Queue using Stacks
用 stack 模拟 queue,肯定是有两个 stack,用一个做不到。就是一个用来进,一个用来出,如果出的 stack 是空,就把进的转移到出的里边,然后出,push 永远是往进的里边 push:
stack<int> sin, sout;
MyQueue() {}
void push(int x) {
sin.push(x);
}
int pop() {
if(sout.empty()) {
while(!sin.empty()) {
const int t = sin.top();
sin.pop();
sout.push(t);
}
}
const int res = sout.top();
sout.pop();
return res;
}
int peek() {
if(sout.empty()) {
while(!sin.empty()) {
const int t = sin.top();
sin.pop();
sout.push(t);
}
}
return sout.top();
}
bool empty() {
return sin.empty() && sout.empty();
}