package com.cb.java.algorithms.datastructure.yanweimindatastructure.list;
/**
* 循环队列
* @author 36184
*
* @param <T>
*/
public class GenericQueue<T> {
private int maxSize; //队列容量
private T[]queue; //队列
private int length=0; //队列中元素个数
private int front=0; //队列头指针
private int rear=-1; //队尾指针
public GenericQueue(int size) {
maxSize=size;
queue=(T[]) new Object[maxSize];
rear=-1;
}
/**
* 向队列中插入元素
* @param x
* @throws Exception
*/
public void insert(T x) throws Exception
{
if(length==maxSize)
{
throw new Exception("队列已满");
}
if(rear==maxSize-1)
rear=-1;
queue[++rear]=x;
length++;
}
/**
* 元素出队
* @return
* @throws Exception
*/
public T remove() throws Exception
{
if(length==0)
throw new Exception("队列中没有元素");
T x=queue[front++];
if(front==maxSize)
front=0;
length--;
return x;
}
/**
* 获取队头元素
* @return
* @throws Exception
*/
public T peek() throws Exception
{
if(length==0)
throw new Exception("队列中没有元素");
return queue[front];
}
/**
* 获取队列中元素个数
* @return
*/
public int length()
{
return length;
}
/**
* 判断队列是否为空
* @return
*/
public boolean isEmpty()
{
return length==0;
}
/**
* 判断队列是否已满
* @return
*/
public boolean isFull()
{
return length==maxSize;
}
}
/**
* 循环队列
* @author 36184
*
* @param <T>
*/
public class GenericQueue<T> {
private int maxSize; //队列容量
private T[]queue; //队列
private int length=0; //队列中元素个数
private int front=0; //队列头指针
private int rear=-1; //队尾指针
public GenericQueue(int size) {
maxSize=size;
queue=(T[]) new Object[maxSize];
rear=-1;
}
/**
* 向队列中插入元素
* @param x
* @throws Exception
*/
public void insert(T x) throws Exception
{
if(length==maxSize)
{
throw new Exception("队列已满");
}
if(rear==maxSize-1)
rear=-1;
queue[++rear]=x;
length++;
}
/**
* 元素出队
* @return
* @throws Exception
*/
public T remove() throws Exception
{
if(length==0)
throw new Exception("队列中没有元素");
T x=queue[front++];
if(front==maxSize)
front=0;
length--;
return x;
}
/**
* 获取队头元素
* @return
* @throws Exception
*/
public T peek() throws Exception
{
if(length==0)
throw new Exception("队列中没有元素");
return queue[front];
}
/**
* 获取队列中元素个数
* @return
*/
public int length()
{
return length;
}
/**
* 判断队列是否为空
* @return
*/
public boolean isEmpty()
{
return length==0;
}
/**
* 判断队列是否已满
* @return
*/
public boolean isFull()
{
return length==maxSize;
}
}