-
队列是一个有序列表,先进先出,可以用数组或者链表来实现
-
初始化队列的头和尾都为-1,入队:队尾增加,对头无变化,随着数据的输入变化而变化;出对:对头变化,队尾不变,随着数据的输出变化而变化;
-
判断队列是否为空的条件:对头=对尾;判断队列是否满的条件:队尾=数组的最大下标减去1;
package JavaSeStudy; import com.sun.source.doctree.ThrowsTree; import java.lang.reflect.Array; import java.util.Scanner; /**数据结构之队列的代码实现 * @author 野望编程小菜鸟 * @computer smartisan * @create 2021-02-01 16:49 */ public class ArrayQueen{ public static void main(String[] args) { Queen q =new Queen(3); char key=' ';//接收用户输入 Scanner sc =new Scanner(System.in); boolean loop=true; while (loop){ System.out.println("s(show):显示队列"); System.out.println("e(exit):退出程序"); System.out.println("a(add):入队"); System.out.println("g(get):出队"); System.out.println("h(head):查看队头的数据"); key=sc.next().charAt(0); switch (key){ case 's': q.showQueue(); break; case 'a': System.out.println("请输入一个数:"); int value =sc.nextInt(); q.addQueue(value); break; case 'g': try{ int res =q.getQueue(); System.out.println("取出的数据是:"+res); } catch (Exception e){ System.out.println(e.getMessage()); } break; case 'h': try{ int res =q.headQueue(); System.out.println("队头的数据是:"+res); } catch (Exception e){ System.out.println(e.getMessage()); } break; case 'e': sc.close(); loop=false; break; default: break; } } System.out.println("程序退出"); } } class Queen { private int maxSize;//数组的最大长度 private int front;//队头 private int rear;//队尾 private int[] arr;//用数组存放数据,模拟队列 public Queen(int arrMaxSize) { //构造器 maxSize = arrMaxSize; front = -1; rear = -1; arr = new int[maxSize]; } //判断队列是否为满 public boolean isFull() { return rear == maxSize - 1; } //判断队列是否为空 public boolean isEmpty() { return rear == front; } //添加数据到队列即入队 public void addQueue(int n) { //判断队列是否满 if (isFull()) { throw new RuntimeException("队列已经满了,无法添加数据"); } rear++; arr[rear] = n; } //获取队列的数据即出队 public int getQueue() { if (isEmpty()) { throw new RuntimeException("队空,无法出队"); } front++;//front后移,因为front为从队列的前一个位置 return arr[front]; } //显示队列的所有数据 public void showQueue() { //遍历 if (isEmpty()) { throw new RuntimeException("队列为空,无法显示"); } for (int i = 0; i < arr.length ; i++) { System.out.printf("arr[%d]=%d\n",i , arr[i]); } } //显示对头 public int headQueue() { if (isFull()) { throw new RuntimeException("队列空,无异常"); } return arr[front + 1]; } }
数据结构之队列
最新推荐文章于 2024-08-15 16:18:00 发布