请你仅使用两个队列实现一个后入先出(LIFO)的栈,并支持普通栈的全部四种操作(push
、top
、pop
和 empty
)。
实现 MyStack
类:
void push(int x)
将元素 x 压入栈顶。int pop()
移除并返回栈顶元素。int top()
返回栈顶元素。boolean empty()
如果栈是空的,返回true
;否则,返回false
。
示例:
输入: ["MyStack", "push", "push", "top", "pop", "empty"] [[], [1], [2], [], [], []] 输出: [null, null, null, 2, 2, false] 解释: MyStack myStack = new MyStack(); myStack.push(1); myStack.push(2); myStack.top(); // 返回 2 myStack.pop(); // 返回 2 myStack.empty(); // 返回 False
用两个单向队列来实现栈:
class MyStack {
public:
queue<int> q1;
queue<int> q2; // 用来备份队列1
MyStack() {
}
void push(int x) {
q1.push(x);
}
int pop() {
int size = q1.size();
size--;
while(size--){
q2.push(q1.front());
q1.pop();
}
int result = q1.front();
q1.pop();
q1 = q2;
while(!q2.empty()){
q2.pop();;
}
return result;
}
int top() {
return q1.back();
}
bool empty() {
return q1.empty();
}
};
用一个队列来实现栈:和使用两个队列的区别主要就是在删除元素时,将被删元素前面的元素加入到队列末尾,此时再去弹出元素就是栈的顺序了。
class MyStack {
public:
queue<int> q1;
//queue<int> q2;
MyStack() {
}
void push(int x) {
q1.push(x);
}
int pop() {
int size = q1.size();
size--;
while(size--){
q1.push(q1.front());
q1.pop();
}
int result = q1.front();
q1.pop();
// q1 = q2;
// while(!q2.empty()){
// q2.pop();;
// }
return result;
}
int top() {
return q1.back();
}
bool empty() {
return q1.empty();
}
};