java 排序队列_java实现顺序队列

packagequeue;importjava.util.Scanner;public classArrayQueueLoop

{public static voidmain(String[] args)

{//TODO Auto-generated method stub//测试代码//测试数组循化队列

CircleQueue testQueue=new CircleQueue(4);//设置的是有效的数据,存在有一个空间作为约定

char key=' ';//接受用户的输入

Scanner in=newScanner(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=in.next().charAt(0);switch(key)

{case 's':

testQueue.showQueue();break;case 'e':

in.close();

loop=false;break;case 'a':

System.out.println("请输入要入队的数字:");int add=in.nextInt();

testQueue.addQueue(add);break;case 'g':try{

System.out.printf("出队的元素为:%d\n",testQueue.getQueue());

}catch(Exception e) {//TODO: handle exception

System.out.println(e.getMessage());

}break;case 'h':try{

System.out.printf("队首元素为:%d\n",testQueue.headQueue());

}catch(Exception e) {//TODO: handle exception

System.out.println(e.getMessage());

}break;default:break;

}

}

System.out.println("退出成功!");

}

}classCircleQueue

{private int maxSize;//数组的最大容量

private int front;//指向队列的头

private int rear;//指向队列的尾部

private int[] arr;//该数组用于存放队列,模拟队列//创建队列的构造器

public CircleQueue(intarrMaxSize)

{

maxSize=arrMaxSize;

arr=new int[maxSize];

front=0;//指向队列的头部,初始值为0

rear=0;//指向队列的尾部的后一个位置,初始值为0

}//判断队列是否满

public booleanisFull()

{return rear==maxSize-1;

}//判断队列是否为空

public booleanisEmpty()

{return rear==front;

}//添加数据到队列

public void addQueue(intn)

{//判断队列是否满了

if(isFull())

{

System.out.println("队列满,不能加入数据!");

}//直接将数据加入就好了

arr[rear]=n;//将rear后移此处必须取模

rear=(rear+1)%maxSize;

}//获取队列的数组,数据出队列

public intgetQueue()

{//判断队列是不是空了

if(isEmpty())

{//抛出异常

throw new RuntimeException("队列空,不能够取数据!");

}else//不为空

{//这里需要分析出,front是队列第一个元素//1.先front的对应的值保存到一个临时的变量//2.front后移//3.将临时保存的变量返回

int value=arr[front];

front=(front+1)%maxSize;returnvalue;

}

}//显示队列所有的数据

public voidshowQueue()

{//简单的遍历

if(isEmpty())

{

System.out.println("队列为空,没有数据!");return;

}//思路从front开始遍历,遍历时候要遍历多少个元素就可以了//要求出当前队列的个数

for(int i=front;i

{

System.out.printf("arr[%d]=%d\n",i%maxSize,arr[i%maxSize]);//注意可能会越界,所以要取模

}

}//返回当前队列有多少元素

public intgetQueueElementNumbers()

{return (rear+maxSize-front)%maxSize;

}//显示队列的头数据,注意不是取出数据

public intheadQueue()

{//判断队列已经为空就没有头数据

if(isEmpty())

{

System.out.println("队列空的,没有数据!");throw new RuntimeException("队列空的,没有数据!");

}returnarr[front];

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值