相关链接
视频讲解:栈的基本操作! | LeetCode:232.用栈实现队列_哔哩哔哩_bilibili
视频讲解:队列的基本操作! | LeetCode:225. 用队列实现栈_哔哩哔哩_bilibili
用栈实现队列
解题思路
用两个栈来实现队列的相关功能,如图所示。
在push数据的时候,只要数据放进输入栈就好,但在pop的时候,操作就复杂一些,输出栈如果为空,就把进栈数据全部导入进来(注意是全部导入),再从出栈弹出数据,如果输出栈不为空,则直接从出栈弹出数据就可以了。
最后如何判断队列为空呢?如果进栈和出栈都为空的话,说明模拟的队列为空了。
AC代码
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() {
int res=this->pop();
stOut.push(res);
return res;
}
bool empty() {
return stIn.empty()&&stOut.empty();
}
};
/**
* Your MyQueue object will be instantiated and called as such:
* MyQueue* obj = new MyQueue();
* obj->push(x);
* int param_2 = obj->pop();
* int param_3 = obj->peek();
* bool param_4 = obj->empty();
*/
用队列实现栈
解题思路
用两个队列和一个队列都可实现对栈的操作,以下为用一个队列实现栈。
AC代码
class MyStack {
public:
queue<int>que;
MyStack() {
}
void push(int x) {
que.push(x);
}
int pop() {
int size=que.size();
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();
}
};
/**
* Your MyStack object will be instantiated and called as such:
* MyStack* obj = new MyStack();
* obj->push(x);
* int param_2 = obj->pop();
* int param_3 = obj->top();
* bool param_4 = obj->empty();
*/
遇到的困难&&总结
之前学习的数据结构仅仅浮于表面,这是第一次用代码实现相关操作,关于STL这方面还是不太熟悉,不过总比模糊的好,对算法有了一些了解。