实现思路:
准备两个队列,push元素时将queue中除了最后一个元素依次poll出并push到辅助队列中,这样queue最后一个元素就是我们要pop的元素,然后我们交换queue和辅助队列的引用方便复用。
代码:
/**
* @description:仅用队列结构实现栈结构
* @Author MRyan
* @Date 2020/5/17 15:00
* @Version 1.0
*/
public class QueueAchieveStack {
//队列
public static Queue<Integer> queue;
//辅助队列
public static Queue<Integer> help;
public static final void main(String[] args) {
init();
push(1);
push(2);
push(3);
push(4);
System.out.println("peek:" + peek());
System.out.println("pop:" + pop());
System.out.println("pop:" + pop());
System.out.println("peek:" + peek());
}
/**
* 初始化
*/
public static void init() {
queue = new LinkedList<>();
help = new LinkedList<>();
}
/**
* 压栈
*
* @param nums
*/
public static void push(int nums) {
queue.add(nums);
}
/**
* 弹出
*
* @return
*/
public static int pop() {
if (queue.isEmpty()) {
throw new RuntimeException("stack is empty");
}
//queue中除了最后一个元素依次poll出并push到辅助队列中
while (queue.size() > 1) {
help.add(queue.poll());
}
//queue中最后一个元素就是要pop的元素
int answer = queue.poll();
//交换queue和help的引用方便复用
swap();
return answer;
}
public static int peek() {
if (queue.isEmpty()) {
throw new RuntimeException("stack is empty");
}
while (queue.size() != 1) {
help.add(queue.poll());
}
int answer = queue.poll();
help.add(answer);
swap();
return answer;
}
/**
* 交换队列和辅助队列引用 方便复用
*/
public static void swap() {
Queue<Integer> temp = queue;
queue = help;
help = temp;
}
}