232.用栈实现队列
题目链接/文章讲解/视频讲解:链接地址
代码思路:队列是先进先出,栈是先进后出,要用栈来实现队列的功能,可以使用两个栈来实现,一个栈用来输入数据,一个栈用来输出数据。
class MyQueue {
public:
stack<int> stack_in;
stack<int> stack_out;
MyQueue() {
}
void push(int x) {
stack_in.push(x);
}
int pop() {
if (stack_out.empty()){
while (!stack_in.empty()) {
stack_out.push(stack_in.top());//C++中栈pop()返回的是少了最后一个元素的数组,不是最后一个元素
stack_in.pop();
}
}
int result = stack_out.top();
stack_out.pop();
return result;
}
int peek() {
int ans = this->pop();
stack_out.push(ans);
return ans;
}
bool empty() {
return stack_in.empty() && stack_out.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();
*/
225. 用队列实现栈
题目链接/文章讲解/视频讲解:链接地址
代码思路:栈是一种先进后出的数据结构,可以使用一个双端队列,封闭掉一个出口来实现。将队列的头部除了最后一个元素都向队列的尾部去添加。
class MyStack {
public:
queue<int> stack;
MyStack() {
}
void push(int x) {
stack.push(x);
}
int pop() {
//将队列头部的元素(除了最后一个元素外)重新添加到队列尾部
if (this->empty()) {
return -1;
}
int size = stack.size();
size--;
while (size--) {
stack.push(stack.front());
stack.pop();//队列是先进先出,pop的是除了第一个元素的数组
}
int result = stack.front();
stack.pop();
return result;
}
int top() {
int ans = this->pop();
stack.push(ans);
return ans;
}
bool empty() {
return stack.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();
*/