开始关于栈与队列的内容。栈是先进后出,队列是先进先出。
今天学习的内容是分别用栈实现队列和用队列实现栈。
第一题、LeetCode232 用栈实现队列 https://leetcode.cn/problems/implement-queue-using-stacks/
用一个进栈和一个出栈实现队列pop先进先出的功能。
注意要在只有stOut为空的时候,才会从stIn导入In中全部的数据,否则Out栈中顺序就错了。此外再peek中得到Out栈顶的元素后,要再把该元素压回栈中,因为peek不改变其第一个元素。
class MyQueue {
public:
stack<int> stIn;
stack<int> stOut;
MyQueue() {
}
void push(int x) {
stIn.push(x);
}
int pop() {
//只有stOut为空的时候,才会从stIn导入数据(全部)
if(stOut.empty()){
while(!stIn.empty()){ //直到empty
//从stIn导入直到in为空
stOut.push(stIn.top());
stIn.pop();
}
}
int result = stOut.top();
stOut.pop();
return result;
}
//Get the first element
int peek() {
int res = this->pop();
stOut.push(res);
return res;//再把该元素添加回去
}
//return whether the stack is empty
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();
*/
第二题、LeetCode225、用队列实现栈 https://leetcode.cn/problems/implement-stack-using-queues/
思路类似,但用队列模拟栈不需要使用两个队列。只需要将队列的出口元素弹出再重新进入队列,直到需要的元素即可。
class MyStack {
public:
queue<int> que;
MyStack() {
}
void push(int x) {
que.push(x);
}
int pop() {
int size = que.size() - 1;
while(size--){// 将队列头部的元素(除了最后一个元素外) 重新添加到队列尾部
que.push(que.front());
que.pop();
}
int res = que.front();// 此时弹出的元素顺序就是栈的顺序了
que.pop();
return res;
}
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();
*/
整体的方法这两道题都是差不多的。