栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Java 1.8使用数组实现循环队列

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java 1.8使用数组实现循环队列

本文实例为大家分享了Java 1.8使用数组实现循环队列的具体代码,供大家参考,具体内容如下

1、引入

使用数组实现循环队列,功能如下:

1)isFull():队列满?
2)isEmpty():队列空?
3)add():添加元素。
4)pop():移除元素。
5)display():展示队列。
6)getSize():获取当前队列元素个数。

2、代码

package DataStructure;

import java.util.Arrays;



public class MyArrayQueue {

 
 private final int DEFAULT_MAX_SIZE = 10;

 
 private int maxSize;

 
 private int front;

 
 private int rear;

 
 private AnyType[] arrQueue;

 
 public MyArrayQueue() {
  this(DEFAULT_MAX_SIZE);
 }//Of the first constructor

 
 public MyArrayQueue(int paraMaxSize) {
  maxSize = paraMaxSize + 1;
  arrQueue = (AnyType[]) new Object[maxSize];
  front = 0;
  rear = 0;
 }//Of the second constructor

 
 public boolean isFull() {
  return (rear + 1) % maxSize == front;
 }//Of isFull

 
 public boolean isEmpty() {
  return front == rear;
 }//Of isEmpty

 
 public void add(AnyType paraVal) {
  if(isFull()) {
   System.out.println("The queue is full.");
   return;
  }//Of if
  arrQueue[rear] = paraVal;
  rear = (rear + 1) % maxSize;
 }//Of add

 
 public AnyType pop() {
  if (isEmpty()) {
   throw new RuntimeException("The queue is full.");
  }//Of if
  AnyType retVal = arrQueue[front];
  front = (front + 1) % maxSize;
  return retVal;
 }//of pop

 
 public void display() {
  if (isEmpty()) {
   System.out.println("The queue is empty.");
   return;
  }//Of if

  System.out.print("The queue is: [");
  int i = front;
  while (i != (rear + maxSize- 1) % maxSize) {
   System.out.printf("%s, ", arrQueue[i]);
   i = (i + 1) % maxSize;
  }//Of while
  System.out.printf("%s]", arrQueue[rear - 1]);
 }//Of display

 
 public int getSize() {
  return (rear - front + maxSize) % maxSize + 1;
 }//Of getSize

 
 public static void main(String[] args) {
  MyArrayQueue  testArrayQueue = new MyArrayQueue<>(3);
  testArrayQueue.add(1);
  testArrayQueue.add(2);
  testArrayQueue.add(4);
  testArrayQueue.pop();
  testArrayQueue.display();
 }//Of main

}//Of MyArrayQueue

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持考高分网。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/130825.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号