我应该在java中使用哪种数据结构来实现一个快速插入的队列,从前面删除,并获取第一个元素的操作?
答案 0 :(得分:3)
LinkedList
不符合条款吗?
其实施
public E remove() {
return removeFirst();
}
public boolean add(E e) {
linkLast(e);
return true;
}
它同时包含first
和last
个节点,因此插入速度很快。您可以使用方法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; }
}