整体思路如下图:
代码实现
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;/*** @author: Arbicoral* @Description: 使用2个队列模拟栈的 push() pop() top(), 自己实现打印 print()*/
public class QueueMoniStack2 {public static void main(String[] args) {QueueMoniStack2 queueMoniStack2 = new QueueMoniStack2();Scanner sc = new Scanner(System.in);System.out.print("请输入要入栈的元素(以-1结尾): ");while (true){int tmp =sc.nextInt();if (tmp!=-1){queueMoniStack2.push(tmp);}else {break;}}// 测试queueMoniStack2.print();queueMoniStack2.push(52);queueMoniStack2.print();queueMoniStack2.push(33);queueMoniStack2.print();queueMoniStack2.top();queueMoniStack2.print();queueMoniStack2.pop();queueMoniStack2.print();queueMoniStack2.pop();queueMoniStack2.print();queueMoniStack2.pop();queueMoniStack2.print();}private void print() {if (queue1.isEmpty()){System.out.println("栈中空空如也~");}else {System.out.print("当前栈中的元素:");queue1.forEach(val-> System.out.print(val + " "));System.out.println();}}private Queue<Integer> queue1=new LinkedList<>();//存数据private Queue<Integer> queue2=new LinkedList<>();// 临时存放// 模拟 push()public void push(Integer n){while (!queue1.isEmpty()){int size = queue1.size();// 1. queue1中的值全部移到queue2while (size-->0){queue2.add(queue1.poll());}}System.out.println("加入元素:" + n);queue1.offer(n);// 2. 将queue2中的值依次加到queue1尾部while (!queue2.isEmpty()){queue1.add(queue2.poll());}}// pop() 弹出栈顶元素public void pop(){Integer poll = queue1.poll();System.out.println("当前栈顶的元素是:" + poll);}// top() 取栈顶元素public void top(){Integer peek = queue1.peek();System.out.println("当前栈顶的元素是:" + peek);}
}
输出结果: