【问题标题】:Dequeue an element from a specific index从特定索引出列元素
【发布时间】:2017-10-18 18:48:45
【问题描述】:

我试图从 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;

}

【问题讨论】:

    标签: java data-structures linked-list queue


    【解决方案1】:

    队列之所以是队列,是因为它有一个入队和出队方法,分别从队列的两端添加和删除。队列不保证提供其他功能。

    如果您想删除中间的特定元素,您可以实现一种算法,在队列中执行此操作 - 例如,将除感兴趣元素之外的每个元素出列到另一个队列中,然后将它们全部重新排入原始队列。

    但是,如果您要从数据结构中删除中间的元素,我怀疑您是否真的想要使用队列。对于其他数据结构,例如(无约束)链接列表或索引数据结构,此操作有更有效的实现。

    【讨论】:

    • 我最终弄明白了。但基本上我是在模拟一家餐馆。当订单进来时,通常他们先到先得,但有时订单需要更长的时间,所以我想添加一个功能,可以查看队列中的前 5 个节点以放入 arrayList,但也能够从前五个节点中的某处出列一个元素来模拟可能是某人刚点了一份沙拉而另一个人点了一份牛排。沙拉显然会先准备好,所以我希望能够将它从队列中取出,即使它不是队列中的第一个。
    猜你喜欢
    • 1970-01-01
    • 2019-03-03
    • 1970-01-01
    • 2015-10-13
    • 1970-01-01
    • 2022-10-14
    • 2013-05-24
    • 1970-01-01
    • 2021-07-16
    相关资源
    最近更新 更多