一、Leetcode第232题:用栈实现队列
思路:一道很基础的题,就是考查对栈的基本操作。用栈来模拟队列的行为,需要一个输入栈,一个输出栈,下面给出随想录的动图(多看几遍)和代码:
class MyQueue {
public:
stack<int> stIn; // 输入栈
stack<int> stOut; // 输出栈
/** Initialize your data structure here. */
MyQueue() {
}
/** Push element x to the back of queue. */
void push(int x) {
stIn.push(x);
}
/** Removes the element from in front of queue and returns that element. */
int pop() {
// 只有当stOut为空的时候,再从stIn里导入数据(导入stIn全部数据)
if (stOut.empty()) {
// 从stIn导入数据直到stIn为空
while(!stIn.empty()) {
stOut.push(stIn.top());
stIn.pop();
}
}
int result = stOut.top();
stOut.pop();
return result;
}
/** Get the front element. */
int peek() {
// this 指针指向调用者(对象),相当于 调用者->pop()
int res = this->pop(); // 直接使用已有的pop函数
stOut.push(res); // 因为pop函数弹出了元素res,所以再添加回去
return res;
}
/** Returns whether the queue is empty. */
bool empty() {
return stIn.empty() && stOut.empty(); // 进栈和出栈都为空,队列为空
}
};
二、Leetcode第232题:用队列实现栈
思路:这题和上题类似,主要考察比较基本的队列操作。可以使用两个队列完成对栈的模拟,一个用来当做栈,另一个用来备份!随想录的图和代码如下:
class MyStack {
public:
queue<int> que1;
queue<int> que2; // auxiliary queue to backed up
/** Initialize your data structure here. */
MyStack() {
}
/** Push element x onto stack. */
void push(int x) {
que1.push(x);
}
/** Remove the element on top of the stack and returns that elements. */
int pop() {
int size = que1.size(); // the length of queue
for(int ii = 0; ii < size - 1; ii++) { // odds should be size - 1
que2.push(que1.front());
que1.pop();
}
int result = que1.front(); // last element
que1.pop();
for(int ii = 0; ii < size - 1; ii++) {
que1.push(que2.front());
que2.pop();
}
// que1 = que2; // 再将que2赋值给que1
// while (!que2.empty()) { // 清空que2
// que2.pop();
// }
return result;
}
/** Get the top element. */
int top() {
return que1.back();
}
/** Return whether the stack is empty. */
bool empty() {
return que1.empty();
}
};
也可以直接使用一个队列就完成这个操作,就是在pop的时候直接把弹出的元素加到队尾,剩最后一个的时候就是 模拟栈 应该弹出的元素!
// 一个队列
class MyStack {
public:
queue<int> que;
/** Initialize your data structure here. */
MyStack() {
}
/** Push element x onto stack. */
void push(int x) {
que.push(x);
}
/** Remove the element on top of the stack and returns that elements. */
int pop() {
int size = que.size(); // the length of queue
for(int ii = 0; ii < size - 1; ii++) { // odds should be size - 1
int ele = que.front();
que.pop();
que.push(ele);
}
int result = que.front(); // the element we need
que.pop();
return result;
}
/** Get the top element. */
int top() {
return que.back();
}
/** Return whether the stack is empty. */
bool empty() {
return que.empty();
}
};