题目描述
原题链接:225. 用队列实现栈
一、两个队列实现栈
其中一个队列用于存当前操作的元素,另一个队列当媒介。
当需要实现对栈顶元素操作功能时,先将queue1中前n-1个元素存入queue2中,此时queue1中剩余的唯一元素便相当于是栈的栈顶元素,弹出即可。
然后,将queue2中元素再重新按原先排列顺序存入queue1中。
class MyStack {
public:
queue<int> que1;
queue<int> que2;
MyStack() {
}
void push(int x) {
que1.push(x);
}
int pop() {
// 将que1中的前n-1个出队,再存入que2中
int n = que1.size() - 1;
while(n--) {
que2.push(que1.front());
que1.pop();
}
// 此时que1中第一个元素便相当于栈顶元素
int res = que1.front();
que1.pop();
// 将que2中所有元素再出队,再存入que1中
n = que2.size();
while(n--) {
que1.push(que2.front());
que2.pop();
}
return res;
}
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();
*/
二、用一个队列实现栈的功能
此时相当于队列循环往复,想输出栈顶元素(也就是队尾元素)时,先将前n-1个元素移动到队尾,直到遍历到最后一个元素时,弹出。
C++版本
class MyStack {
public:
queue<int> que;
MyStack() {
}
void push(int x) {
que.push(x);
}
int pop() {
// 将前n-1个元素一定到队尾
int n = que.size() - 1;
while(n--) {
que.push(que.front());
que.pop();
}
// 第n个元素相当于栈顶元素,此时它位于队头,弹出
int res = que.front();
que.pop();
return res;
}
int top() {
// 队尾元素(第n个元素)相当于是栈顶元素
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();
*/
Python版本
class MyStack:
def __init__(self):
self.que = []
def push(self, x: int) -> None:
self.que.append(x)
def pop(self) -> int:
for i in range(len(self.que) - 1):
self.que.append(self.que.pop(0))
return self.que.pop(0)
def top(self) -> int:
return self.que[-1]
def empty(self) -> bool:
return not self.que
# Your MyStack object will be instantiated and called as such:
# obj = MyStack()
# obj.push(x)
# param_2 = obj.pop()
# param_3 = obj.top()
# param_4 = obj.empty()
时间复杂度:弹出栈顶元素pop、获取栈顶元素top的实现复杂度为 O ( n ) O(n) O(n),其余时间复杂度为 O ( 1 ) O(1) O(1)。
空间复杂度 O ( n ) O(n) O(n)
参考文章:225. 用队列实现栈