重学数据结构(六)——使用数组实现环形队列

使用数组实现环形队列

package com.codezs.datastruct.queue;

public class CircleQueue {

    private String[] items;

    private int size = 0;
    //指向队列头部
    private int head = 0;
	//指向队列尾部
    private int tail = 0;

    public CircleQueue(int capacity) {
        items = new String[capacity];
        this.size = capacity;
    }

    //入队
    public boolean enqueue(String item) {
        //队列已满
        if ((tail + 1) % size == head) return false;

        items[tail] = item;
        tail = (tail + 1) % size;
        return true;
    }

    //出队
    public String dequeue() {
        //队列为空时
        if (head == tail) return null;

        String temp = items[head];
        head = (head + 1) % size;
        return temp;
    }
}

posted @ 2020-08-04 11:41  zsiscool  阅读(95)  评论(0编辑  收藏  举报