【数组q[n]用来表示一个循环队列】Java用数组实现循环队列的示例

更新时间:2021-08-23    来源:js教程    手机版     字体:

【www.bbyears.com--js教程】

复习了下数据结构,用Java的数组实现一下循环队列。

队列的类

//循环队列
class CirQueue{
 private int QueueSize;
 private int front;
 private int rear;
 private int[] queueList ;
 
 public CirQueue(int QueueSize){
  this.QueueSize = QueueSize; 
  queueList = new int[QueueSize];
  front = 0;
  rear = 0;
 }
 
 //获取队列头元素
 public int getQueueElement(){
  //如果队列不为空,返回队头元素,否则抛出异常提示队列为空
  int element = -1;
  if(!isEmpty()){
   element = queueList[front];
   return element;
  }
  else {
   System.out.println("队列为空");
   return -1;
  }
  
 }
 
 //出队
 public int deQueue(){
  int element = -1;
  if(!isEmpty()){
   element = queueList[front];
   front =(front+1)%QueueSize;
   return element;
  }
  else {
   System.out.println("队列为空");
   return -1;
  }
  
 }
 
 
 
 
 
 //入队
 public void enQueue(int element){
  //如果队列未满,添加元素到队尾,否则提示队列已满
  if(!isFull()){
   queueList[rear] = element ;
   rear = (rear+1)%QueueSize;
   
  }
  else {
   System.out.println("队列已满");
  }
 }
 
 //判断队列是否为空
 public boolean isEmpty(){
  boolean b = false;
  if(rear == front)
   b = true;
  return b;
 }
 
 
 //判断队列是否已满
 public boolean isFull(){
  boolean b = false;
  if((rear+1)%QueueSize == front)
   b = true;
  return b;
 }

}

创建对象并测试

package com.test;

import java.util.*;


public class StructTest {

 /**
  * @param args
  */
 public static void main(String[] args) {
  // TODO Auto-generated method stub
  
  //新建并初始化存储空间为3的循环队列(方便判断队满条件,浪费一个数组空间)
  CirQueue cirQueue = new CirQueue(4);
  //入队3个元素
  cirQueue.enQueue(1);
  cirQueue.enQueue(2);
  cirQueue.enQueue(3);
  
  //获取队头元素,获取 但不改变队列
  int temp = cirQueue.getQueueElement();
  System.out.println(temp);
  
  //出队 获取队头元素,并且队头指针往后移一位
  temp = cirQueue.deQueue();
  System.out.println(temp);
  
  //再次获取队头元素
  temp = cirQueue.getQueueElement();
  System.out.println(temp);
  
  
 }

}

输出:

1
1
2

本文来源:http://www.bbyears.com/wangyezhizuo/137600.html

猜你感兴趣