整体思路如下图所示:
代码实现:
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
/**
* @author: Arbicoral
* @Description: 使用一个队列模拟栈的 push() pop() top(), 自己实现打印 print()
*/
public class QueueMoniStack1 {
public static void main(String[] args) {
// 输入元素入栈
QueueMoniStack1 queueMonStack = new QueueMoniStack1();
System.out.print("请输入要入栈的元素(以-1结尾): ");
Scanner sc = new Scanner(System.in);
while (true){
int tmp = sc.nextInt();
if (tmp!=-1){
queueMonStack.push(tmp);
}else {
break;
}
}
// 测试
queueMonStack.print1();
queueMonStack.push(52);
queueMonStack.print2();
queueMonStack.push(9);
queueMonStack.print2();
queueMonStack.top();
queueMonStack.print2();
queueMonStack.pop();
queueMonStack.print2();
queueMonStack.pop();
queueMonStack.print2();
queueMonStack.pop();
queueMonStack.print2();
}
private Queue<Integer> queue = new LinkedList<>();
// 使用一个队列模拟栈的加入元素操作,即push()
public void push(Integer n){
System.out.println("加入元素:" + n);
queue.offer(n);//
int size = queue.size();
while (size-->1){// 移动 size-1 次
int temp=queue.poll();
queue.offer(temp);
}
}
// pop() 移除栈顶元素
public void pop(){
System.out.println("移除栈顶元素:" + queue.poll());
}
// top() 取栈顶元素
public void top(){
Integer peek = queue.peek();
System.out.println("当前栈顶的元素是:" + peek);
}
// 打印当前栈中的元素 ---方法一:使用 增强for 打印
public void print1(){
if (queue.isEmpty()){
System.out.println("栈中空空如也~");
}else {
System.out.print("当前栈中的元素:");
queue.forEach(var -> System.out.print(var + " "));// 增强for循环
System.out.println();
}
}
// 打印当前栈中的元素 ---方法二 使用普通的遍历方法
public void print2(){
if (queue.isEmpty()){
System.out.println("栈中空空如也~");
}else {
System.out.print("当前栈中的元素:");
int size = queue.size();
while (size-->0){// 移动 size 次
Integer tmp = queue.poll();//取出来
System.out.print(tmp + " ");
queue.add(tmp);// 再恢复回去
}
System.out.println();
}
}
}
输出结果: