具有快速插入,删除和前端元素java的Fifo队列

时间:2013-08-23 19:11:08

标签: java queue

我应该在java中使用哪种数据结构来实现一个快速插入的队列,从前面删除,并获取第一个元素的操作?

2 个答案:

答案 0 :(得分:3)

LinkedList不符合条款吗?

其实施

public E remove() {
    return removeFirst();
}

public boolean add(E e) {
    linkLast(e);
    return true;
}

它同时包含firstlast个节点,因此插入速度很快。您可以使用方法remove()从前面删除。你也可以得到第一个元素,即。 peek()返回first节点。这也是O(1)

来源

void linkLast(E e) {
    final Node<E> l = last;
    final Node<E> newNode = new Node<>(l, e, null);
    last = newNode;
    if (l == null)
        first = newNode;
    else
        l.next = newNode;
    size++;
    modCount++;
}

答案 1 :(得分:2)

LinkedBlockingQueue完成这项工作。 take()要抓取put()进行插入。

如果您的队列是固定大小,ArrayBlockingQueue将更有效。

或者,如果您必须自己实现快速固定大小的队列:

public class Queue<T> {
    private T[] q;
    private int head = 0;
    private int tail = 0;
    private int used = 0;
    private int size;

    @SuppressWarnings("unchecked")
    public Queue(int size) {
        q = (T[]) new Object[size];
        this.size = size;
    }
    public synchronized void put(T o) throws InterruptedException {
        while(isFull()) {
            wait();
        }
        q[head] = o;
        head = (head+1) % size;
        used++;
        notifyAll();
    }
    public synchronized T take() throws InterruptedException {
        while(isEmpty()) {
            wait();
        }
        T result = q[tail];
        tail = (tail+1) % size;
        used--;
        notifyAll();
        return result;
    }
    public synchronized boolean isEmpty() { return used == 0; }
    public synchronized boolean isFull() { return used == size; }
}