This commit is contained in:
youngyangyang04
2020-07-23 19:24:24 +08:00
parent 9dcd5e3d2e
commit 6e5620132e
3 changed files with 34 additions and 37 deletions

View File

@ -4,6 +4,8 @@ https://leetcode-cn.com/problems/implement-stack-using-queues/
## 思路
有的同学可能疑惑这种题目有什么实际工程意义,其实很多算法题目主要是对知识点的考察和教学意义远大于其工程实践的意义,所以面试题也是这样!
用栈实现队列, 和用队列实现栈的思路还是不一样的,这取决于这两个数据结构的性质
建议大家题目编号: 225 和 232 一起做来做
@ -15,8 +17,8 @@ https://leetcode-cn.com/problems/implement-stack-using-queues/
```
class MyStack {
public:
queue<int> queIn;
queue<int> queOut;
queue<int> que1;
queue<int> que2; // 辅助队列
/** Initialize your data structure here. */
MyStack() {
@ -24,35 +26,35 @@ public:
/** Push element x onto stack. */
void push(int x) {
queIn.push(x);
que1.push(x);
}
/** Removes the element on top of the stack and returns that element. */
int pop() {
int size = queIn.size();
int size = que1.size();
size--;
while (size--) { // 将queIn 导入queOut,但要留下最后一个元素
queOut.push(queIn.front());
queIn.pop();
while (size--) { // 将que1 导入que2,但要留下最后一个元素
que2.push(que1.front());
que1.pop();
}
int result = queIn.front(); // 留下的最后一个元素就是我们要返回的值
queIn.pop();
queIn = queOut; // 再将queOut赋值给queIn
while(!queOut.empty()) { // 清空queOut
queOut.pop();
int result = que1.front(); // 留下的最后一个元素就是我们要返回的值
que1.pop();
que1 = que2; // 再将que2赋值给que1
while(!que2.empty()) { // 清空que2
que2.pop();
}
return result;
}
/** Get the top element. */
int top() {
return queIn.back();
return que1.back();
}
/** Returns whether the stack is empty. */
bool empty() {
return queIn.empty();
return que1.empty();
}
};
```

View File

@ -23,9 +23,11 @@ public:
/** Removes the element from in front of queue and returns that element. */
int pop() {
if (stOut.empty()) { //只有当stOut为空的时候再从stIn里导入数据
//只有当stOut为空的时候再从stIn里导入数据导入stIn全部数据
if (stOut.empty()) {
// 从stIn导入数据直到stIn为空
while(!stIn.empty()) {
stOut.push(stIn.top()); // 从stIn导入数据知道stOut为空
stOut.push(stIn.top());
stIn.pop();
}
}
@ -47,14 +49,6 @@ public:
}
};
/**
* 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();
*/
```
> 更过算法干货文章持续更新可以微信搜索「代码随想录」第一时间围观关注后回复「Java」「C++」 「python」「简历模板」「数据结构与算法」等等就可以获得我多年整理的学习资料。