栈与队列理论基础
文章链接:栈与队列理论基础
Leetcode 232.用栈实现队列
题目链接:232.用栈实现队列
思路:一个栈当作入栈,一个栈当作出栈 或者 只操作一个栈,另外一个栈当备份即可
自己做法:
class MyQueue {
public:
stack<int> st1;
stack<int> st2;
MyQueue() {
}
void push(int x) {
st1.push(x);
}
int pop() {
int temp = 0;
while(!st1.empty()) {
temp = st1.top();
st1.pop();
if(st1.empty()) break;
st2.push(temp);
}
while(!st2.empty()) {
int tmp = st2.top();
st2.pop();
st1.push(tmp);
}
return temp;
}
int peek() {
int temp = 0;
while(!st1.empty()) {
temp = st1.top();
st1.pop();
st2.push(temp);
}
while(!st2.empty()) {
int tmp = st2.top();
st2.pop();
st1.push(tmp);
}
return temp;
}
bool empty() {
if(st1.empty()) return true;
else return false;
}
};
/**
* 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();
*/
代码随想录做法:
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 result = this->pop();
stOut.push(result);
return result;
}
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();
*/
Leetcode 225.用队列实现栈
题目链接:225.用队列实现栈
思路:两个队列第二个队列只是用来备份而已,一个队列在模拟栈弹出元素的时候只要将队列头部的元素(除了最后一个元素外) 重新添加到队列尾部,此时再去弹出元素就是栈的顺序了。
两个队列实现栈:
class MyStack {
public:
queue<int> que1;
queue<int> que2;
MyStack() {
}
void push(int x) {
que1.push(x);
}
int pop() {
int size = que1.size();
size --;
while(size --) {
que2.push(que1.front());
que1.pop();
}
int result = que1.front();
que1.pop();
while(!que2.empty()) {
que1.push(que2.front());
que2.pop();
}
return result;
}
int top() {
return que1.back();
}
bool empty() {
return que1.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();
*/
单个队列实现栈:
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();
*/