本篇题目
● 232.用栈实现队列
● 225. 用队列实现栈
232.用栈实现队列
232.用栈实现队列
本篇需要了解栈和容器的基本概念及实现原理。
本题实现队列,可以使用两个栈来模拟实现队列的接口。
class MyQueue2 {
public:
MyQueue2() {
}
// 在队列末尾加入元素
void push(int x) {
_stack.push(x);
}
// 队头元素弹出并返回
int pop() {
while (!_stack.empty()) {
int val = _stack.top();
_stack.pop();
_tmpStack.push(val);
}
int ret = -1;
if (!_tmpStack.empty()) {
ret = _tmpStack.top();
_tmpStack.pop();
}
while (!_tmpStack.empty()) {
int val = _tmpStack.top();
_tmpStack.pop();
_stack.push(val);
}
return ret;
}
// 队头元素返回
int peek() {
while (!_stack.empty()) {
int val = _stack.top();
_stack.pop();
_tmpStack.push(val);
}
int ret = -1;
if (!_tmpStack.empty())
ret = _tmpStack.top();
while (!_tmpStack.empty()) {
int val = _tmpStack.top();
_tmpStack.pop();
_stack.push(val);
}
return ret;
}
// 队列是否为空
bool empty() {
return _stack.empty();
}
private:
stack<int> _stack;
stack<int> _tmpStack;
};
225. 用队列实现栈
// 最好画图来验证是否正确
// 栈的弹出元素我的思路是错误的
// 相当于弹出了栈底元素
class MyStack {
public:
void push(int x) {
_queue.push(x);
}
int pop() {
// 弹出_queue除了最后一个元素前的所有元素
while (_queue.size() > 1){
int val = _queue.front();
_queue.pop();
_tmpQueue.push(val);
}
// 获取最后一个栈顶元素
int ret = -1;
if (!_queue.empty()) {
ret = _queue.front();
_queue.pop();
}
// 重新还原到_queue
while (!_tmpQueue.empty()) {
int val = _tmpQueue.front();
_tmpQueue.pop();
_queue.push(val);
}
return ret;
}
int top() {
return _queue.back();
}
bool empty() {
return _queue.empty();
}
int size() {
return _queue.size();
}
private:
queue<int> _queue;
queue<int> _tmpQueue;
};