Java数组队列,使用数组实现队列,队列

标准类:

public class ArrayQueue{       //队列,由队尾插入元素,由队首删除元素
 private int[] A;     //内置数组
 private int front;   //头指针
 private int rear;    //尾指针

public ArrayQueue(int size) {
  this.A=new int[size];
  front=0;
  rear=-1;   //初始化队列
 }  //kuimeng
 public boolean Empty(){
     return front == A.length;   //判断队列为空
 }
 public boolean Full() {
     return A.length - 1 == rear;   //判断队列为满
 }
 public void insert(int Element) {
  if(Full()) {
   throw new Error("队列已满");
  }  //kuimeng
  A[++rear]=Element;   //在队列的队尾插入元素
 }
 public int leader() {
     return A[front];     //获取队首元素
 }
 public int end() {
  return A[rear];      //获取队尾元素
 }
 public int Removal() {
  if(Empty()) {
   throw new Error("队列为空"); 
  }
  return A[front++];    //删除队首元素
  }}//kuimeng

测试类:

public class ArrayQueueTest {
public static void main(String[] args) {
  // TODO Auto-generated method stub
ArrayQueue queue=new ArrayQueue(20);
  System.out.println("---------------------------------------------------");
  System.out.println("队列是否为空?:"+queue.Empty());
  //kuimeng
  System.out.println("---------------------------------------------------");
  for(int i=0;i<20;i++) {
   queue.insert(i);
  }
  System.out.println("队列是否已满?:"+queue.Full());
  System.out.println("---------------------------------------------------");
  System.out.println("队首元素为:"+queue.leader());
  System.out.println("---------------------------------------------------");
  System.out.println("队尾元素为:"+queue.end());
  System.out.println("---------------------------------------------------");
  System.out.println("队列所有元素为:");
  while(!queue.Empty()) {  //kuimeng
   System.out.println(+queue.Removal());
  }
  System.out.println("---------------------------------------------------");
  }}

运行结果:

---------------------------------------------------
队列是否为空?:false
---------------------------------------------------
队列是否已满?:true
---------------------------------------------------
队首元素为:0
---------------------------------------------------
队尾元素为:19
---------------------------------------------------
队列所有元素为:
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
---------------------------------------------------

对小编的代码有兴趣的朋友们记得点赞关注哟~

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值