All Downloads are FREE. Search and download functionalities are using the official Maven repository.

net.intelie.pipes.util.TreeQueue Maven / Gradle / Ivy

There is a newer version: 0.25.5
Show newest version
package net.intelie.pipes.util;

import net.intelie.pipes.Tree;

import java.util.Arrays;

public class TreeQueue {
    private int head = 0, tail = 0;
    private Tree[] list;

    public TreeQueue() {
        this(16);
    }

    public TreeQueue(int size) {
        list = new Tree[size];
    }

    public boolean isEmpty() {
        return head == tail;
    }

    public void enqueue(Tree tree) {
        while (next(tail) == head) {
            grow();
        }
        list[tail] = tree;
        tail = next(tail);
    }

    public Tree get(int index) {
        int size = size();
        return list[(head + (index % size + size) % size) % list.length];
    }

    private int next(int index) {
        return (index + 1) % list.length;
    }

    private void grow() {
        int size = size();
        int newSize = list.length + (list.length >> 1);

        Tree[] newList = new Tree[newSize];

        System.arraycopy(list, head, newList, 0, list.length - head);
        System.arraycopy(list, 0, newList, list.length - head, head);

        head = 0;
        tail = size;
        list = newList;
    }

    public int size() {
        return (tail - head + list.length) % list.length;
    }

    public Tree dequeue() {
        Tree e = list[head];
        list[head] = null;
        head = next(head);
        return e;
    }

    public void clear() {
        Arrays.fill(list, null);
        head = tail = 0;
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy