数组实现简单队列

对于队列来说,需要队首和队尾指针变量,出队改变队首,入队改变队尾。此外需要队列的大小和存放数据的变量。代码如下:

public class ArrayQueue {
    
    

    private int maxSize;
    private int[] queue;
    private int front;  //队首
    private int rear;   //队尾

    public ArrayQueue(int maxSize){
    
    
        this.maxSize = maxSize;
        this.queue = new int[maxSize];
        this.front = -1; 		// 队首指向首元素的前一个位置,取数据前需要先+1
        this.rear = -1;		// 队尾指向最后一个元素,所以也是先+1,再存数据
    }

    public boolean isFull(){
    
    
        return rear == maxSize-1;
    }

    public boolean isEmpty(){
    
    
        return rear == front;
    }

    // 入队
    public void add(int value){
    
    
        if(isFull()){
    
    
            System.out.println("队列已满");
            return;
        }
        rear++;
        queue[rear] = value;
    }

    // 出队
    public int get(){
    
    
        if(isEmpty()){
    
    
            throw new RuntimeException("队列为空");
        }
        front++;
        int value = queue[front];
        return value;
    }

	// 遍历队列
    public void show(){
    
    
        if(isEmpty()){
    
    
            System.out.println("队列为空");
            return;
        }
        for (int i = front+1; i <= rear; i++) {
    
    
            System.out.printf("arr[%d]=%d\n", i, queue[i]);
        }
    }

    // 查看队首
    public int head(){
    
    
        if(isEmpty()){
    
    
            throw new RuntimeException("队列为空");
        }
        int value = queue[front+1];
        return value;
    }
}

测试代码:

public class Test {
    
    
    public static void main(String[] args){
    
    
        // 队列 ---- 数组实现,不可重复使用
        ArrayQueue arrayQueue = new ArrayQueue(10);
        arrayQueue.add(1);
        arrayQueue.add(2);
        arrayQueue.add(3);
        System.out.println(arrayQueue.get());
        arrayQueue.show();
        System.out.println(arrayQueue.head());
    }
}

Guess you like

Origin blog.csdn.net/never_late/article/details/118577638