环形队列结构

/* 环形队列(Queue)。队列简称队。是一种操作受限的线性表,只允许在表的一端进行插入,而在表的另一端进行删除。向队列中插入元素称为入队或进队;删除元素称为出队或离队。
其操作特性为先进先出(First In First Out,FIFO),并且只允许在队尾进,队头出。*/
public class RingQueue {

    public static void main(String[] args) {
        RingNode node = new RingNode(3);
        for (int i = 0; i < 9; i++) {
            System.out.println("队列有效个数:" + node.getAll());
            node.add(i);
            System.out.println("第" + (i + 1) + "次添加");
            if (i % 2 == 1) {
                System.out.println("拿出数据:" + node.get());
            }
            System.out.println("========================");
        }
    }
}

class RingNode {

    public int front = 0; //头指针指向最前面的元素
    public int real = 0;  //尾指针指向最后面的元素后一个位置
    public int maxsize;  //创建队列的大小
    public Object[] arr; //创建容器


    public RingNode(int maxsize) {

        this.arr = new Object[maxsize];
        this.maxsize = maxsize;
    }

    public void add(Object o) {

        if (isFull()) {
            //
            System.out.println("队列已满");
            return;
        }
        //添加数据
        arr[real] = o;
        System.out.printf("添加:arr[%d]=%d\n", real % maxsize, arr[real % maxsize]);//arr[0]=1
        real = (real + 1) % maxsize; //取余


    }

    public Object get() {
        if (!isEmpty()) {
            System.out.printf("拿出:arr[%d]=%d\n", front % maxsize, arr[front % maxsize]);//arr[0]=1
            Object a = arr[front% maxsize];
            arr[front% maxsize] = null;
            front = (front + 1) % maxsize;
            return a;
        }
        return null;
    }

    /*满*/
    public boolean isFull() {
        return ((real + 1) % maxsize) == front;
    }

    /*空*/
    public boolean isEmpty() {
        return real == front;
    }

    /*有效数据个数*/
    public int getAll() {

        for (int i = front; i < front + (((real + maxsize - front) % maxsize)); i++) {

            System.out.printf("剩余:arr[%d]=%d\n", i % maxsize, arr[i % maxsize]);//arr[0]=1
        }
        return (real + maxsize - front) % maxsize;
    }


}

你可能感兴趣的:(数据结构和算法,java,数据结构,开发语言)