数组模拟循环队列



import java.util.Scanner;
/**
 * 
 * 数组模拟循环队列
 *
 */
public class CircleArrayQueueDemo {
     
	public static void main(String[] args){
     
		boolean flag=true;
		CircleArrayQueue queue=new CircleArrayQueue(4);
		Scanner s=new Scanner(System.in);
		while(flag){
     
			 System.out.println("1.显示队列元素:");
			 System.out.println("2.添加元素到队列:");
			 System.out.println("3.取出元素从队列:");
			 System.out.println("4.队列的头元素:");
			 System.out.println("5.退出程序:");
			 System.out.print("请输入要执行的序号:");
			 int x=s.nextInt();
			 
			 switch(x){
     
			 case 1:
		    	  queue.showQueue();
		    	  System.out.println();
		    	  break;
		      case 2:
		    	  System.out.print("请输入要添加的元素:");
		    	  int value=s.nextInt();
		    	  queue.addQueue(value);
		    	  break;
		      case 3:
		    	  int y=queue.getQueue();
		    	  System.out.println(y);
		    	  break;
		      case 4:
		    	  int z=queue.getHeadQueue();
		    	  System.out.println(z);
		    	  break;
		      case 5:
		    	  s.close();
		    	  flag=false;
		    	  break;
		      default:
		    	  break;
		  }
		}
	}
}

class CircleArrayQueue{
     
	private int a[];
	private int front;
	private int rear;
	private int Maxsize;
	public CircleArrayQueue(int Maxsize){
     
		this.Maxsize=Maxsize;
		int front=0;
		int rear=0;
		a=new int[Maxsize];
	}
	public boolean isFull(){
     
		return (rear+1)%Maxsize==front;
	}
	public boolean isEmpty(){
     
		return front==rear;
	}
	public void addQueue(int n){
     
		if(isFull()){
     
			System.out.print("队列已满!");
			return;
		}
		a[rear]=n;
		rear=(rear+1)%Maxsize;
	}
	public int getQueue(){
     
		if(isEmpty()){
     
			throw new RuntimeException("队列为空!");
		}
		int getqueue=a[front];
		front=(front+1)%Maxsize;
		return getqueue;
	}
	public void showQueue(){
     
		if(isEmpty()){
     
			System.out.println("队列为空!");
			return;
		}
		for(int i=front;i<front+(rear+Maxsize-front)%Maxsize;i++){
     
			System.out.print(a[i%Maxsize]);
		}
	}
	public int getHeadQueue(){
     
		if (isEmpty()) {
     
			throw new RuntimeException("队列空的,没有数据~~");
		}
		return a[front];
	}
}

你可能感兴趣的:(数据结构,java,数据结构)