java实现环形队列

selfup

环形队列

  • 队列是一种先进先出的数据结构

代码思路

  • 用数组存放队列的数据
  • front指向队首元素
  • rear指向队尾元素
  • num存放当前已经存在的元素个数,有了num,判断队列是否为空是否存满比较方便
public class Demo2 {
    public static void main(String[] args) {
        ArrayQueue queue = new ArrayQueue(5);
        queue.addNum(10001);
        queue.addNum(10002);
        queue.addNum(10003);
        queue.addNum(10004);
        queue.addNum(10005);
        System.out.println(queue.getNum());
        System.out.println(queue.getNum());
        queue.addNum(1);
        queue.addNum(2);
        queue.addNum(3);
        queue.showQueue();
        System.out.println(queue.getNum());
        System.out.println(queue.getNum());
        System.out.println(queue.getNum());
        System.out.println(queue.getNum());
        System.out.println(queue.getNum());
        System.out.println(queue.getNum());
    }
}

class ArrayQueue {
    //队列的大小
    int maxSize;
    //用数组来实现队列
    int[] arr;
    //指向队列首元素
    int front;
    //指向队列尾元素
    int rear;
    //当前队列的元素的个数
    int num;

    public ArrayQueue(int maxSize) {
        this.maxSize = maxSize;
        this.arr = new int[this.maxSize];
        front = -1;
        rear = -1;
    }


    public boolean isFull() {
        return num == maxSize;
    }


    public boolean isEmpty() {
        return num == 0;
    }


    public void addNum(int num) {
        if (isFull()) {
            System.out.println("队列已满,无法在进行入队操作");
            return;
        }
        //队尾标记后移,指向要放入的元素的位置
        if (front == -1 && rear == -1) {
            front = 0;
            rear = 0;
        } else {
            rear = rear + 1;
        }
        if (rear == maxSize) {
            rear = 0;
        }
        arr[rear] = num;
        this.num++;
    }

    public int getNum() {
        if (isEmpty()) {
            throw new RuntimeException("队列为空,无法出队");
        }
        //队首标记后移,指向队首元素
        System.out.print("出队元素是:");
        this.num--;
        int res = arr[front];
        front++;
        if (front == maxSize) {
            front = 0;
        }
        return res;
    }

    public void showQueue() {
        if (isEmpty()) {
            throw new RuntimeException("队列为空,无法遍历");
        }
        System.out.println("遍历队列");
        if (rear >= front) {
            for (int start = front; start <= rear; start++) {
                System.out.println(arr[start]);
            }
        } else {
            for (int start = front; start <= maxSize - 1; start++) {
                System.out.println(arr[start]);
            }
            for (int start = 0; start <= rear; start++) {
                System.out.println(arr[start]);
            }
        }
    }
}
阅读 203

...说点什么吧

5 声望
2 粉丝
0 条评论
你知道吗?

...说点什么吧

5 声望
2 粉丝
宣传栏