用数组实现一个循环队列

public class RoundQueue {
    private String[] items;
    private int n;
    private int front;
    private int rear;

    public RoundQueue(int capacity) {
        this.items = new String[n];
        this.n = capacity;
        this.front = 0;
        this.rear = 0;
    }

    public boolean enqueue(String item) {
        if ((rear + 1) % n == front) {
            System.out.println("队列已满");
            return false;
        }
        items[rear] = item;
        rear = (rear + 1) % n;
        return true;
    }

    public String dequeue() {
        if (front == rear) {
            System.out.println("队列为空");
            return null;
        }
        String result = items[front];
        front = (front + 1) % n;
        return result;
    }
    public void printAll() {
        if (0 == n) return;
        for (int i = front; i % n != rear; i = (i + 1) % n) {
            System.out.print(items[i] + " ");
        }
        System.out.println();
    }
}

写对循环队列代码的关键就在于队空和队满的判断,技巧可以参看我的另一篇博客:

如何判断循环队列为队空or队满? 里面还有循环队列的其他实现思路。

发布了91 篇原创文章 · 获赞 22 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_42006733/article/details/104361595