队列(2023-02-02) 使用数组模拟队列(未优化) 1.需要用的变量有front=-1,rear=-1,maxsize以及数组int[] arr; 2.判断队列已满的条件是rear==maxsize-1,队列为空的条件是rear==front; 3.入队是需要判断队列是否已满且rear的后移条件是为rear++,出队是需要判断队列是否为空(以抛出异常的方式提示)front++
throw new RuntimeException("队列为空");
4.队列长度为maxsize,即遍历输出队列的时候的循环终止条件是maxsize
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
使用数组模拟队列(优化后) 1.需要用的变量有front=0,rear=0,maxsize以及数组int[] arr; 2.判断队列已满的条件是(rear+1)%maxsize,队列为空的条件是rear==front; 3.入队是需要判断队列是否已满且rear的后移条件为(rear+1)%maxsize,出队是需要判断队列是否为空(以抛出异常的方式提示),front的后移条件是(front+1)%maxsizethrow new RuntimeException("队列为空");
4.队列长度为 (rear+Maxsize-front)%Maxsize ,即遍历输出队列的时候的循环终止条件是front+ size()
size()为函数,函数体就是(rear+Maxsize-front)%Maxsize
类:
package com.zyk.Queue; public class Queue { private int Maxsize; private int front; private int rear; private int[] arr; public Queue(int maxsize) { Maxsize = maxsize; arr=new int[Maxsize]; } public boolean isFull(){ //return rear==Maxsize-1; return (rear+1)%Maxsize==front;//优化算法 } public boolean isEmpty(){ return front==rear; } public void AddQueue(int n){ if(isFull()){ System.out.println("队列已满"); return; } // rear++; // arr[rear]=n; arr[rear]=n; rear=(rear+1)%Maxsize; } public int GetQueue(){ if(isEmpty()){ throw new RuntimeException("队列为空"); } // front++; // return arr[front]; int value =arr[front]; front=(front+1)%Maxsize; return value; } public void ShowQueue() { if (isEmpty()) { System.out.println("队列为空"); return; } // for(int i=0;i<Maxsize;i++){ // System.out.printf(arr[i]+"\t"); // } // } //循环从front开始,结束条件是队列的有效个数 for (int i = front; i <front+ size(); i ++) { System.out.printf("arr[%d]=%d\n",i%Maxsize,arr[i%Maxsize]); } } //计算有效的队列个数 public int size(){ return (rear+Maxsize-front)%Maxsize; } }
主函数:
package com.zyk.Queue; import java.util.Scanner; public class ArrayQueue { public static void main(String[] args) { //有效长度只有3,所以只能输入三个数据,输入第四个数据时会提示已满,这是因为有一个rear和front约定的空间 Queue queue = new Queue(4); String key=""; boolean loop=true; Scanner scanner = new Scanner(System.in); do { System.out.println("\n\t\t\t1 显示队列"); System.out.println("\t\t\t2 入队"); System.out.println("\t\t\t3 出队"); System.out.println("\t\t\t4 退出系统"); System.out.println("请输入选项"); key=scanner.next(); switch (key){ case"1": queue.ShowQueue(); break; case"2": System.out.println("请输入数据"); int value=scanner.nextInt(); queue.AddQueue(value); break; case"3": try { int res=queue.GetQueue(); System.out.println(res); }catch(Exception e){ System.out.println(e.getMessage()); } break; case"4": scanner.close(); loop=false; break; } }while(loop); System.out.println("已退出......"); } }
标签:10,队列,Java,--,System,int,front,println,rear From: https://www.cnblogs.com/copyjames/p/17086716.html