Java数据结构学习笔记2——循环队列
核心逻辑代码如下:
class CircleQueue
{
private int maxSize = 0 ;
private int front ;
private int rear ;
private int [ ] arr;
public CircleQueue ( int arrMaxSize)
{
maxSize= arrMaxSize;
arr = new int [ maxSize] ;
front= 0 ;
rear = 0 ;
}
public boolean isEmpty ( )
{
return rear== front;
}
public boolean isFull ( )
{
return ( rear+ 1 ) % maxSize== front;
}
public void push ( int data)
{
if ( isFull ( ) )
{
throw new RuntimeException ( "the circle queue is full" ) ;
}
arr[ rear] = data;
rear= ( rear+ 1 ) % maxSize;
}
public int pop ( )
{
if ( isEmpty ( ) )
{
throw new RuntimeException ( "the circle queue is empty" ) ;
}
int value= arr[ front] ;
front= ( front + 1 ) % maxSize;
return value;
}
public void showAllDataFromQueue ( )
{
if ( isEmpty ( ) )
{
System. out. println ( "the queue is empty" ) ;
return ;
}
for ( int i= ( front ) % maxSize; i< front+ getCapacity ( ) ; i++ )
{
System. out. printf ( "arr[%d] = %d\n" , i % maxSize, arr[ i % maxSize] ) ;
}
}
public int getHead ( )
{
if ( isEmpty ( ) )
{
throw new RuntimeException ( "the circle que is empty" ) ;
}
return arr[ front] ;
}
public int getMaxSize ( )
{
return maxSize;
}
public int getCapacity ( )
{
return ( rear+ maxSize- front) % ( maxSize) ;
}
}