完整代码
package com.jzoffer.stackandqueue;
import java.util.Scanner;
import java.util.Stack;
class CQueue {
private Stack<Integer> stack1;
private Stack<Integer> stack2;
public CQueue() {
this.stack1 = new Stack<>();
this.stack2 = new Stack<>();
}
public void appendTail(int value) {
while (!stack2.isEmpty()) {
stack1.push(stack2.pop());
}
stack1.push(value);
}
public int deleteHead() {
while (!stack1.isEmpty()) {
stack2.push(stack1.pop());
}
if (stack2.isEmpty()) {
System.out.println("队列为空");
return -1;
}
System.out.printf("队首元素%d已删除",stack2.peek());
System.out.println();
return stack2.pop();
}
public void showQueue() {
while (!stack1.isEmpty()) {
stack2.push(stack1.pop());
}
if (stack2.isEmpty()) {
System.out.println("队列为空");
}
if (!stack2.isEmpty()) {
System.out.println("队列如下(队首---队尾)");
for (int index = stack2.size() - 1; index >= 0; index--) {
System.out.printf("%d ", stack2.get(index));
}
System.out.println();
}
}
}
public class CQueueDemo {
public static void main(String[] args) {
CQueue q = new CQueue();
Scanner in = new Scanner(System.in);
char key = ' ';
boolean loop = true;
while (loop) {
System.out.println("a---添加元素");
System.out.println("d---删除队首元素");
System.out.println("s---显示队列");
System.out.println("q---退出");
System.out.println("请选择操作:");
key = in.next().charAt(0);
switch (key) {
case 'a' :
System.out.println("请输入一个数字");
int val = in.nextInt();
q.appendTail(val);
break;
case 'd' :
q.deleteHead();
break;
case 's' :
q.showQueue();
break;
case 'q' :
loop = false;
break;
default:
break;
}
}
in.close();
}
}
运行截图
|