2017-10-18 94 views
0

我试图从LinkedNode队列中取出特定元素。这是我从另一个方法中得到的,它只是删除并返回队列中的第一个节点(因为它应该在队列中)。我的问题是如何编辑,以便它将删除索引x处的元素?我包括javadoc psudocode希望有所帮助。从特定索引中取出元素

/** 
* Removes and returns the element that is at place x in the queue. 
* Precondition: x must be less than 5, x must be less than size 
* Note: indexing from 0: 0 == front element, 1 == second element, etc. 
* @param x the passed in index of the element to be removed 
* @return the element removed from the queue 
* @throws EmptyCollectionException if the queue is empty 
* @throws InvalidArgumentException if x > 4, or x > size of collection 
* 
*/ 

public T dequeue(int x) throws EmptyCollectionException { 
    if (numNodes == 0) { 
     throw new EmptyCollectionException("Work Ahead Queue"); 
    } 
    T element = front.getElement(); 
    front = front.getNext(); 
    firstFive.remove(0); 
    numNodes--; 
    if (numNodes >= 5) { 
     firstFive.add(firstFive.get(3).getNext()); 
    } 
    return element; 

} 

回答

0

队列是一个队列,因为它有一个入队和出队方法,其中分别添加和从队列中移出的相对端。不保证队列提供其他功能。

如果你想在中间移除特定元素,你可以实现的算法,这是否上的队列 - 例如,出列,每个元素除了元素的兴趣到另一个队列,然后排队他们再次回到原来的队列中。然而,如果你打算从数据结构中删除中间的元素,我怀疑你真的想要使用一个队列。对其他数据结构(如(无约束)链接列表或索引数据结构)上的此操作有更高效的实现。

+0

我最终弄明白了。但基本上我是在模拟一家餐馆。随着订单的进入,通常它们会先到先得,但有时订单需要更长的时间,所以我想添加一个功能 ,它可以窥探队列中的前5个节点放入arrayList,但也可以从第一个五个节点的某个地方出列一个元素来模拟可能是某人刚点了一份沙拉而另一个则点了一份牛排。沙拉显然已经准备好了,所以我希望能够把它从队列中取出,即使它不是队列中的第一个。 – Ryan