package com.hao.firstdemo.datastruct;
/**
* @author haoxiansheng
*/
public class TestQueue {
public static void main(String[] args) {
ArrayQueue arrayQueue = new ArrayQueue(7);
arrayQueue.addQueue(4);
System.out.println(arrayQueue.isEmpty());
arrayQueue.show();
arrayQueue.popQueue();
System.out.println(arrayQueue.isEmpty());
}
}
// 使用数组模拟队列-编写一个ArryQueue类
class ArrayQueue {
private int maxSize; //表示数组的最大容量
private int front; //队列头部
private int rear; // 队列尾部
private int[] arr; //存放数据
/**
* 创建队列构造器
*
* @param arryMaxSize
*/
public ArrayQueue(int arryMaxSize) {
maxSize = arryMaxSize;
arr = new int[maxSize];
front = -1; //指向队列头部,指向队列头的前一个位置
rear = -1; //指向队列尾部, 指向队列尾部数据(队列最后一个数据)
}
/**
* 判断队列是否满了
*
* @return
*/
public boolean isFull() {
return rear == maxSize - 1;
}
/**
* 判断队列是否为空
* @return
*/
public boolean isEmpty() {
return rear == front;
}
/**
* 添加数据
*
* @param n
*/
public void addQueue(int n) {
if (isFull()) {
System.out.println("队列已满不能添加数据");
return;
}
rear++; //指针往后移
arr[rear] = n;
}
/**
* 获取队列数据 出队
*
* @return
*/
public int popQueue() {
if (isEmpty()) {
System.out.println("队列中不存在数据");
throw new RuntimeException("队列为空,不能取数据");
}
front++;
return arr[front];
}
/**
* 显示数据
*/
public void show() {
if (isEmpty()) {
System.out.println("队列中没有数据");
}
for (int i = 0; i < arr.length; i++) {
System.out.printf("arr[%d]=%d\n", i, arr[i]);
}
}
/**
* 显示队列的头数据
* @return
*/
public int headQueue() {
if (isEmpty()) {
throw new RuntimeException("队列空的没有数据");
}
return arr[front+1];
}
}