请你仅使用两个队列实现一个后入先出(LIFO)的栈,并支持普通栈的全部四种操作(push、top、pop 和 empty)。
实现 MyStack 类:
void push(int x) 将元素 x 压入栈顶。
int pop() 移除并返回栈顶元素。
int top() 返回栈顶元素。
boolean empty() 如果栈是空的,返回 true ;否则,返回 false 。
注意:
1、你只能使用队列的基本操作 —— 也就是 push to back、peek/pop from front、size 和 is empty 这些操作。
2、你所使用的语言也许不支持队列。 你可以使用 list (列表)或者 deque(双端队列)来模拟一个队列 , 只要是标准的队列操作即可。
示例:
输入:
["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
提示:
1、1 <= x <= 9
2、最多调用100 次 push、pop、top 和 empty
3、每次调用 pop 和 top 都保证栈不为空
思路:
empty方法:new两个队列,如果两个队列均为空,则栈为空
push方法:向不空的队列放元素,一开始默认向第一个队列放
pop方法:若第一个队列有n个元素,则弹出一个元素进入队列2,重复n-1次,队列1最后剩下的元素就是需要弹出的元素
top方法:pop方法剩下的最后一个元素返回之后,将其弹出再放入另一个队列
代码:
class MyStack {
private Queue<Integer> qu1;
private Queue<Integer> qu2;
public MyStack() {
qu1=new LinkedList<>();
qu2=new LinkedList<>();
}
public void push(int x) {
if(!qu1.isEmpty()){
qu1.offer(x);
}else if(!qu2.isEmpty()){
qu2.offer(x);
}else{
qu1.offer(x);
}
}
public int pop() {
if(empty()){
return -1;
}
if(!qu1.isEmpty()){
int size=qu1.size();
for(int i=0;i<size-1;i++){
int x=qu1.poll();
qu2.offer(x);
}
return qu1.poll();
}else{
int size=qu2.size();
for(int i=0;i<size-1;i++){
int x=qu2.poll();
qu1.offer(x);
}
return qu2.poll();
}
}
public int top() {
if(empty()){
return -1;
}
if(!qu1.isEmpty()){
int x=-1;
int size=qu1.size();
for(int i=0;i<size;i++){
x=qu1.poll();
qu2.offer(x);
}
return x;
}else{
int x=-1;
int size=qu2.size();
for(int i=0;i<size;i++){
x=qu2.poll();
qu1.offer(x);
}
return x;
}
}
public boolean empty() {
if(qu1.isEmpty()&&qu2.isEmpty()){
return true;
}
return false;
}
}