文章
问答
冒泡
自定义实现循环列表
/**
 * 条件为循环数组中插入的是非负数。
 */


public class MyCircularQueue {


    private int[] data;
    private int head, tail, size;


    public MyCircularQueue(int k){
        data = new int[k];
        head = tail = -1;
        size = k;
    }


    public boolean enQueue(int value) {
        if(isEmpty()) {
            head = 0;
        }
        if(isFull()) {
            return false;
        }
        tail = (tail + 1) % size; 
        data[tail] = value;
        return true;
    }


    public boolean deQueue() {
        if(isEmpty()) {
            return false;
        }
        /** 注意此部分的特殊情况判断,当为空的时候直接将数组的指针直接 */
        if( head == tail) {
            head = tail = -1;
            return true;
        }
        head = (head + 1) % size;
        return true;
    
    }


    public boolean isFull() {
        return (tail + 1) % size == head;
    }


    public boolean isEmpty(){
        return head == -1;
    }


    public int getFont() {
        if(isEmpty()) {
            return -1;
        }
        return data[head];
    }


    public int getLast() {
        if(isEmpty()) {
            return -1;
        }
        return data[tail];
    }
}

代码示例

数据结构与算法
循环列表

关于作者

Kirago
个人站点 https://kiragoo.github.io/
获得点赞
文章被阅读