题目一:232. 用栈实现队列
初见:第一次做栈的算法题,在许多方面没有总结,造成了代码的多余
思路:
1. 需要熟悉栈和队列的运用
2. 熟悉c++的栈和队列的语法
代码:
class MyQueue {
public:
stack<int> stIn;
stack<int> stOut;
MyQueue() {
}
//进栈和出栈都有函数实现
void push(int x) {
stIn.push(x);
}
int pop() {
if(stOut.empty())
{
while(!stIn.empty())
{
stOut.push(stIn.top());
stIn.pop();
}
}
//pop()并不会返回值,错误
//int result = stOut.pop();
int result = stOut.top();
stOut.pop();
return result;
}
int peek() {
int result = this->pop();
stOut.push(result);
return result;
}
bool empty() {
if(stIn.empty() && stOut.empty()) return true;
return false;
}
};
题目二:225. 用队列实现栈
初见:这题跟第一题差不多,考的都是栈和队列的运用
代码:
class MyStack {
public:
queue<int> q1;
queue<int> q2;
//析构函数,初始化
MyStack() {
}
void push(int x) {
q1.push(x);
}
int pop() {
while(q1.size() != 1)
{
q2.push(q1.front());
q1.pop();
}
int result = q1.front();
q1.pop();
//出栈后将队列2的元素调入队列1
q1 = q2;
while(!q2.empty())
{
//q2 可以直接赋值给 q1 ,q1 = q2;
//q1.push(q2.front());
q2.pop();
}
return result;
}
int top() {
int temp = q1.back();
return temp;
}
bool empty() {
if(!q1.empty()) return false;
return true;
}
};