キューの最下層実装(配列とリング配列)

2715 ワード

隊列は順序正しいリストで、原則:先入先出
簡単な配列実現:frontはキューヘッドの前の位置を指します。rearは列の最後の位置を指します。frontとrearの初期値は全部-1です。
//        --    ArrayQueue 
class ArrayQueue{
	private int  maxSize;
	private int array[];
	private int front;
	private int rear;
	
	//              
	public ArrayQueue(int maxSize) {
	    this.maxSize=maxSize;
	    array=new int[maxSize];
	    front=-1;
	    rear=-1;
	    
	}
	
    //        
	public boolean isEmpty() {
		
		return  front==-1&&rear==-1;
	}
	
    //       
	public boolean isFull() {
		
		return rear==maxSize-1;
	}
	
    //        
	public void addQueue(int n) {
		//       
		if(isFull()) {
			System.out.println("    ~~");
		}else {
			rear++;
			array[rear]=n;
		}
	}
	
	//       
	public int getQueue() {
	   //      
		if(isEmpty()) {
			throw new RuntimeException("    ");
		}else {
			front++;
			return array[front];
		}
	}
	
	//        
	public void showQueue() {
		if(isEmpty()) {
			throw new RuntimeException("    ");
		}
		for(int i=front+1;i<=rear;i++) {
			System.out.printf("arry[%d]=%d
",i,array[i]); } } // public int headQueue() { if(isEmpty()) { throw new RuntimeException(" "); } return array[front+1]; } }
上記のコードで実現されたキューには問題があります。配列は一回しか使えません。多重化の効果がないため、配列シミュレーションリング行列を使います。1、frontとrear調整:frontは列の最初の要素を指し、rearは列の最後の要素の後の位置を指します。rear=frontキューいっぱい:(rear+1)%maxSize=front;キューの有効データ個数:(rear+maxSize-front)%maxsizeこの具体的な分析はデータ構造の本を見ることができます。具体的な例を探して、絵を描く人は理解できます。。
class CircleArrayQueue{
	//          
	private int  maxSize; 
	private int array[];
	private int front;  //          
	private int rear;   //              
	
	//              
	public CircleArrayQueue(int maxSize) {
        this.maxSize=maxSize;
		array=new int[maxSize];
		front=0;
	    rear=0;   
		}
	
	//        
	public boolean isEmpty() {
		
	  return  front==rear;
		}
	
	//       
	public boolean isFull() {
		 return (rear+1)%maxSize==front;
	}
	
	//            
	public int size(){
		return (rear+maxSize-front)%maxSize;
	}
	//          
	public void addQueue(int n) {
		
		if(isFull()) {
			System.out.println("    ~~");
			return;
		}
		 array[rear]=n;
		 rear=(rear+1)%maxSize;
		
	}
	
	//       
	public int getQueue() {
	   //      
			if(isEmpty()) {
				throw new RuntimeException("    ~~");
			}else {
				int value=array[front];
				front=(front+1)%maxSize;
				return value;
			}
		}
	
	//        
	public void showQueue() {
			if(isEmpty()) {
				throw new RuntimeException("    ");
			}
			for(int i=front;i