232.用栈实现队列
1.自己的想法
我的想法很简单,用另一个栈作为辅助空间,负责将原本的栈颠倒过来
class MyQueue {
public:
MyQueue() {
}
void push(int x) {
st1.push(x);
}
int pop() {
while (!st1.empty())
{
st2.push(st1.top());
st1.pop();
}
int tmp = st2.top();
st2.pop();
while (!st2.empty())
{
st1.push(st2.top());
st2.pop();
}
return tmp;
}
int peek() {
while (!st1.empty())
{
st2.push(st1.top());
st1.pop();
}
int tmp = st2.top();
while (!st2.empty())
{
st1.push(st2.top());
st2.pop();
}
return tmp;
}
bool empty() {
return st1.empty();
}
private:
stack<int> st1; //作为队列
stack<int> st2; //作为辅助
};
2.代码随想录提供的思路,一个输入栈,一个输出栈
class MyQueue {
public:
MyQueue() {
}
void push(int x) {
st1.push(x);
}
int pop() {
if (st2.empty())
{
while (!st1.empty())
{
st2.push(st1.top());
st1.pop();
}
}
int res = st2.top();
st2.pop();
return res;
}
int peek() {
int res = this->pop();
st2.push(res);
return res;
}
bool empty() {
return st1.empty() && st2.empty();
}
private:
stack<int> st1; //作为输入栈
stack<int> st2; //作为输出栈
};
225. 用队列实现栈
1.我自己想的
我的想法:每次入队时都用辅助队列帮其挪到队头。
class MyStack {
public:
MyStack() {
}
void push(int x) {
q2.push(x);
while (!q1.empty())
{
q2.push(q1.front());
q1.pop();
}
while (!q2.empty())
{
q1.push(q2.front());
q2.pop();
}
}
int pop() {
int res = q1.front();
q1.pop();
return res;
}
int top() {
int res = q1.front();
return res;
}
bool empty() {
return q1.empty();
}
private:
queue<int> q1; //以其为栈
queue<int> q2; //辅助空间
};
2.代码随想录版本,可以把尾部前的元素全部重新入队
class MyStack {
public:
MyStack() {
}
void push(int x) {
q.push(x);
}
int pop() {
int n = q.size() - 1;
while (n--)
{
q.push(q.front());
q.pop();
}
int res = q.front();
q.pop();
return res;
}
int top() {
return q.back();
}
bool empty() {
return q.empty();
}
private:
queue<int> q; //以其为栈
};