2017-10-18 149 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