Use an array to simulate a circular queue
The meaning of the front variable is adjusted, front points to the first element of the queue, that is, arr[front] is the first element of the queue. The initial value of front is 0
The meaning of the rear variable is adjusted, and rear points to a position after the last element of the queue. Because I want to make a space. The initial value of rear is 0
Judgment that the queue is full: (rear + 1)% maxSize == front
Judgment of empty queue: rear == front
The number of valid values in the queue: (rear-front + maxSize)% maxSize
Code
import java. util. Scanner;
public class CircleQueueDemo {
public static void main ( String[ ] args) {
CircleQueue circleQueue = new CircleQueue ( 3 ) ;
Scanner scanner = new Scanner ( System. in) ;
char key = ' ' ;
boolean loop = true ;
while ( loop) {
System. out. println ( "s(show)" ) ;
System. out. println ( "a(add)" ) ;
System. out. println ( "g(get)" ) ;
System. out. println ( "e(exit)" ) ;
System. out. println ( "h(head)" ) ;
key = scanner. next ( ) . charAt ( 0 ) ;
switch ( key) {
case 's' :
circleQueue. showQueue ( ) ;
break ;
case 'a' :
System. out. println ( "请输入一个数" ) ;
try {
int temp1 = scanner. nextInt ( ) ;
circleQueue. addQueue ( temp1) ;
} catch ( Exception e) {
e. printStackTrace ( ) ;
}
break ;
case 'g' :
try {
System. out. println ( circleQueue. getQueue ( ) ) ;
} catch ( Exception e) {
e. printStackTrace ( ) ;
}
break ;
case 'e' :
loop = false ;
break ;
case 'h' :
System. out. println ( circleQueue. headQueue ( ) ) ;
break ;
default :
break ;
}
}
System. out. println ( "退出程序" ) ;
}
}
class CircleQueue {
private int maxSize;
private int front;
private int rear;
private int [ ] arr;
public CircleQueue ( int maxSize) {
this . maxSize = maxSize;
front = 0 ;
rear = 0 ;
arr = new int [ maxSize] ;
}
public boolean isFull ( ) {
return ( rear + 1 ) % maxSize == front;
}
public boolean isEmpty ( ) {
return rear == front;
}
public int size ( ) {
return ( rear + maxSize - front) % maxSize;
}
public void addQueue ( int n) {
if ( isFull ( ) ) {
System. out. println ( "队列满" ) ;
return ;
}
arr[ rear] = n;
rear = ( rear + 1 ) % maxSize;
}
public int getQueue ( ) {
if ( isEmpty ( ) ) {
throw new RuntimeException ( "队列空" ) ;
}
int value = arr[ front] ;
front = ( front + 1 ) % maxSize;
return value;
}
public int headQueue ( ) {
if ( isEmpty ( ) ) {
throw new RuntimeException ( "队列空" ) ;
}
return arr[ front] ;
}
public void showQueue ( ) {
if ( isEmpty ( ) ) {
System. out. println ( "队列空" ) ;
return ;
}
for ( int i = front; i < front + size ( ) ; i++ ) {
System. out. printf ( "arr[%d] = %d" , i% maxSize, arr[ i% maxSize] ) ;
System. out. println ( ) ;
}
}
}