题目: 请你仅使用两个队列实现一个后入先出(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 MyQueue {
public:
queue<int> q1, q2;
MyQueue(){}
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();
}
};
int main() {
MyQueue q;
q.push(1);
q.push(2);
cout<<q.pop()<<endl;//2
q.push(3);
cout<<q.top()<<endl;//3
q.push(4);
cout << q.pop() << endl;//4
cout << q.pop() << endl;//3
cout << q.pop() << endl;//1
return 0;
}
使用一个队列实现栈
class MyStack {
public:
queue<int> q;
MyStack() {
}
void push(int x) {
q.push(x);
}
int pop() {
int size = q.size();
size--;
while (size--) {
q.push(q.front());
q.pop();
}
int result = q.front();
q.pop();
return result;
}
int top() {
return q.back();
}
bool empty() {
return q.empty();
}
};
int main() {
MyStack q;
q.push(1);
q.push(2);
cout<<q.pop()<<endl;//2
q.push(3);
cout<<q.top()<<endl;//3
q.push(4);
cout << q.pop() << endl;//4
cout << q.pop() << endl;//3
cout << q.pop() << endl;//1
return 0;
}