package case07_StackWithTwoQueues;
/**
*题目:用两个队列实现栈,并且实现栈的pop,push,isEmpty,top(获取栈顶元素,但是不删除)
* @author WangSai
*
*/
import java.util.*;
public class StackWithTwoQueues<T> {
// 两个队列,在模拟实现栈的时候,始终保持其中一个队列为空。
private final Queue<T> queue1 = new ArrayDeque<>();
private final Queue<T> queue2 = new ArrayDeque<>();
public boolean push(T t) {
if (!queue1.isEmpty()) {
queue1.offer(t);
} else if (!queue2.isEmpty()) {
queue2.offer(t);
} else {
queue1.offer(t);
}
return true;
}
public T pop() {
if (!queue1.isEmpty()) {
while (queue1.size() > 1) {
queue2.offer(queue1.poll());
}
return queue1.poll();
} else if (!queue2.isEmpty()) {
while (queue2.size() > 1) {
queue1.offer(queue2.poll());
}
return queue2.poll();
} else {
return null;
}
}
public T top() {
T top = null;
if (!queue1.isEmpty()){
while (!queue1.isEmpty()){
top = queue1.poll();
queue2.offer(top);
}
return top;
} else if (!queue2.isEmpty()) {
while (!queue2.isEmpty()) {
top = queue2.poll();
queue1.offer(top);
}
}
return top;
}
public boolean isEmpty() {
return queue1.isEmpty() && queue2.isEmpty();
}
public static void main(String[] args) {
StackWithTwoQueues<String> myStack = new StackWithTwoQueues<>();
myStack.push("1st e");
myStack.push("2nd e");
myStack.push("3rd e");
System.out.println("第1次:myStack.pop():"+myStack.pop());
System.out.println("第3次:myStack.pop():"+myStack.pop());
System.out.println("myStack.top():"+myStack.top());
System.out.println("第2次:myStack.pop():"+myStack.pop());
System.out.println("第4次:myStack.pop():"+myStack.pop());
}
}
剑指offer-面试题07-衍生题目:用两个队列实现栈
最新推荐文章于 2023-05-16 12:01:35 发布