232.用栈实现队列
题目
使用栈实现队列的下列操作:
push(x) -- 将一个元素放入队列的尾部。
pop() -- 从队列首部移除元素。
peek() -- 返回队列首部的元素。
empty() -- 返回队列是否为空。
思考
经过昨天KMP的洗礼后,今天看stack实在太开心了,主要自己还做过这题,难题其实就在于pop那个环节,要做到先进先出需要两个栈来完成:stIn将首元素依次放入到stOut底部,stOut将原先为底部的元素pop出来,peek也是这么个原理,只是不需要pop而已,不难
代码
class MyQueue {
stack<int> stIn, stOut;
public:
MyQueue() {}
void push(int x) {
stIn.push(x);
}
int pop() {
if(stOut.empty()) {
while(!stIn.empty()) {
stOut.push(stIn.top());
stIn.pop();
}
}
int res = stOut.top();
stOut.pop();
return res;
}
int peek() {
if(stOut.empty()) {
while(!stIn.empty()) {
stOut.push(stIn.top());
stIn.pop();
}
}
return stOut.top();
}
bool empty() {
if(stIn.empty() && stOut.empty()) return true;
return false;
}
};
225. 用队列实现栈
题目
使用队列实现栈的下列操作:
- push(x) -- 元素 x 入栈
- pop() -- 移除栈顶元素
- top() -- 获取栈顶元素
- empty() -- 返回栈是否为空
思考
这题之前没做,想了很久以为需要用两个栈来做,其实没那么复杂,用一个栈即可完成,自己也先将代码给写出来了:就是将栈顶部的元素依次放入底部,每遍历一次就pop一下,遍历的次数为 size() -1(注意这里尤为关键,因为原先栈最底部的元素不用再操作了);遍历完后弹出queue.front()即可,top就更简单,直接返回queue.back()(因为返回的是栈顶元素);
代码
class MyStack {
queue<int> que;
public:
MyStack() {}
void push(int x) {
que.push(x);
}
int pop() {
if(que.empty()) return NULL;
int size = que.size() - 1;//底部的数会变成顶部,所以只需要操作size-1次即可
while(size--) {
int tmp = que.front();
que.pop();
que.push(tmp);
}
int res = que.front();
que.pop();
return res;
}
int top() {
return que.back();
}
bool empty() {
return que.empty();
}
};