队列
用数组模拟队列
用两个变量来记录队列的前后
front:随着数据的输出而改变
rear:随着数据的输入而改变
当添加数据时候 指针往后移动 rear + 1 当 front == rear 时队列为空
若指针 rear 小于队列的最大下标则存入,否则无法存入,队列满判断:rear == maxSize - 1
import java.util.Scanner; public class ArrayQueueDemo { public static void main(String[] args) { ArrayQueue arrayQueue = new ArrayQueue(3); char key = ' '; Scanner scanner = new Scanner(System.in); boolean loop = true; while (loop){ System.out.println("s 显示队列"); System.out.println("e 退出程序"); System.out.println("a 添加数据到队列"); System.out.println("g 从队列取出数据"); System.out.println("h 查看队列头数据"); key = scanner.next().charAt(0); switch (key){ case 's': arrayQueue.showQueue(); break; case 'e': scanner.close(); loop = false; break; case 'a': System.out.println("请输入"); int value = scanner.nextInt(); arrayQueue.addQueue(value); break; case 'g': try { int res = arrayQueue.getQueue(); System.out.printf("取出数据为%d\n", res); } catch (Exception e){ System.out.println(e.getMessage()); } break; case 'h': try { int res = arrayQueue.headQueue(); System.out.printf("队列头数据为%d\n", res); } catch (Exception e){ System.out.println(e.getMessage()); } break; } System.out.println("程序退出"); } } } class ArrayQueue { private int maxSize; private int front; private int rear; private int[] arr; public ArrayQueue(int arrMaxSize) { maxSize = arrMaxSize; arr = new int[maxSize]; front = -1; rear = -1; } public boolean isFull() { return rear == maxSize - 1; } public boolean isEmpty() { return front == rear; } public void addQueue(int n) { if (isFull()) { System.out.println("队列已满"); return; } arr[++rear] = n; } public int getQueue() { if (isEmpty()) { throw new RuntimeException("队列为空"); } return arr[++front]; } public void showQueue() { if (isEmpty()) { System.out.println("队列为空"); return; } for (int i = 0; i < arr.length; i++) { System.out.printf("arr[%d]=%d\n", i, arr[i]); } } public int headQueue() { if (isEmpty()) { throw new RuntimeException("队列为空"); } return arr[front + 1]; } }
根据自我理解改写

浙公网安备 33010602011771号