普通队列
public class QueueByArray {
public static void main ( String args[ ] )
{
ArrayQueue arrayQueue= new ArrayQueue ( 4 ) ;
int x= arrayQueue. DeQueue ( ) ;
arrayQueue. EnQueue ( 1 ) ;
arrayQueue. EnQueue ( 2 ) ;
arrayQueue. EnQueue ( 3 ) ;
arrayQueue. EnQueue ( 4 ) ;
arrayQueue. EnQueue ( 5 ) ;
arrayQueue. showQueue ( ) ;
x= arrayQueue. DeQueue ( ) ;
System. out. println ( x) ;
int y= arrayQueue. topQueue ( ) ;
System. out. println ( y) ;
arrayQueue. showQueue ( ) ;
}
}
class ArrayQueue {
int maxSize;
int front;
int rear;
int arr[ ] ;
public ArrayQueue ( int maxSize)
{
this . maxSize= maxSize;
front= - 1 ;
rear= - 1 ;
arr= new int [ maxSize] ;
}
public void EnQueue ( int elem)
{
if ( rear== maxSize- 1 )
{
System. out. println ( "队列已满,不能再添加" ) ;
return ;
}
rear++ ;
arr[ rear] = elem;
System. out. println ( "添加成功" ) ;
}
public int DeQueue ( )
{
if ( rear== front)
{
System. out. println ( "队列已空" ) ;
return - 1 ;
}
System. out. println ( "出队成功" ) ;
return arr[ ++ front] ;
}
public int topQueue ( )
{
if ( rear== front)
{
System. out. println ( "队列已空" ) ;
return - 1 ;
}
return arr[ front+ 1 ] ;
}
public boolean isFull ( )
{
return rear== maxSize- 1 ;
}
public boolean isEmpty ( )
{
return rear== front;
}
public void showQueue ( )
{
if ( rear== front)
{
System. out. println ( "队列已空" ) ;
return ;
}
for ( int i= front+ 1 ; i<= rear; i++ )
System. out. print ( arr[ i] + " " ) ;
System. out. println ( ) ;
}
}
循环队列
public class CircleQueue {
public static void main ( String args[ ] )
{
QueueCircle queueCircle= new QueueCircle ( 3 ) ;
queueCircle. DeQueue ( ) ;
queueCircle. EnQueue ( 1 ) ;
queueCircle. EnQueue ( 2 ) ;
queueCircle. showQueue ( ) ;
queueCircle. EnQueue ( 3 ) ;
queueCircle. EnQueue ( 4 ) ;
queueCircle. DeQueue ( ) ;
queueCircle. EnQueue ( 4 ) ;
queueCircle. showQueue ( ) ;
}
}
class QueueCircle {
int maxSize;
int front;
int rear;
int arr[ ] ;
public QueueCircle ( int maxSize)
{
this . maxSize= maxSize;
front= 0 ;
rear= 0 ;
arr= new int [ maxSize] ;
}
public void EnQueue ( int elem)
{
if ( ( rear+ 1 ) % maxSize== front)
{
System. out. println ( "队列已满,不能再添加" ) ;
return ;
}
arr[ rear] = elem;
rear= ( rear+ 1 ) % maxSize;
System. out. println ( "添加成功" ) ;
}
public int DeQueue ( )
{
if ( rear== front)
{
System. out. println ( "队列已空" ) ;
return - 1 ;
}
System. out. println ( "出队成功" ) ;
int value= arr[ front] ;
front= ( front+ 1 ) % maxSize;
return value;
}
public int topQueue ( )
{
if ( rear== front)
{
System. out. println ( "队列已空" ) ;
return - 1 ;
}
return arr[ front] ;
}
public boolean isFull ( )
{
return rear+ maxSize- front== maxSize;
}
public boolean isEmpty ( )
{
return rear== front;
}
public void showQueue ( )
{
if ( rear== front)
{
System. out. println ( "队列已空" ) ;
return ;
}
for ( int i= front; i< front+ size ( ) ; i++ )
System. out. print ( arr[ i] + " " ) ;
System. out. println ( ) ;
}
public int size ( )
{
return ( rear- front+ maxSize) % maxSize;
}
}