题目链接:232. 用栈实现队列
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();
}
}
int result=stOut.top();
stOut.pop();
return result;
}
int peek()
{
if(stOut.empty()){
while(!stIn.empty()){
stOut.push(stIn.top());
stIn.pop();
}
}
return stOut.top();
// int res=pop();
// stOut.push(res);
// return res;
//也可以直接调用上面的pop函数,然后再将res添加回去
}
bool empty()
{
return stIn.empty()&&stOut.empty();
}
};
虽然学过数据结构,对队列和栈的特性比较了解,但是还是第一次使用c++里面的stack或queue,以前都是自己模拟写一个栈之类的,学到了这种用法,感觉比自己写栈要方便多了。
- 时间复杂度: push和empty为O(1), pop和peek为O(n)
- 空间复杂度: O(n)
题目链接:225. 用队列实现栈
用2个队列实现,一个用来输入输出,一个用来备份
class MyStack
{
public:
queue<int> qMain;
queue<int> qBackup;
MyStack()
{
}
void push(int x)
{
qMain.push(x);
}
int pop()
{
int size=qMain.size();
while(--size){
qBackup.push(qMain.front());
qMain.pop();
}
int result=qMain.front();
qMain.pop();
// while(!qBackup.empty()){
// qMain.push(qBackup.front());
// qBackup.pop();
// }
qMain=qBackup;
while(!qBackup.empty()){
qBackup.pop();
}
return result;
}
int top()
{
// int result=pop();
// qMain.push(result);
// return result;
return qMain.back();
}
bool empty()
{
return qMain.empty();
}
};
用一个队列代码更少,就是把这个队列的头元素重新添加到尾部
class MyStack//只用一个队列的方法,即将队尾之前的元素重新入队
{
public:
queue<int> que;
MyStack()
{
}
void push(int x)
{
que.push(x);
}
int pop()
{
int size=que.size();
while(--size){
que.push(que.front());
que.pop();
}
int result=que.front();
que.pop();
return result;
}
int top()
{
return que.back();
}
bool empty()
{
return que.empty();
}
};
通过这两个题目,学到了stack和queue的一些基本操作和区别,
pop是无返回值的
stack的top是取栈顶
队列可以取头元素front,也可以取尾元素back