【问题标题】:Remove any object inserted in a LinkedList implemented as Queue删除插入作为队列实现的 LinkedList 中的任何对象
【发布时间】:2020-01-24 12:12:16
【问题描述】:

我有一个作为队列实现的 LinkedList。 remove(object) 方法可以删除队列中任意位置的对象,据我所知,这与队列的先进先出的概念相矛盾。我对此的理解是错误的。

Queue<Object> q= new LinkedList<>();
//assuming objects have been inserted 
q.remove(a); //this removes the object 'a' present anywhere in the Queue.

【问题讨论】:

  • 好吧,如果你不想移除队列中任何地方的元素,就不要调用这个方法。
  • 好的,但是这种方法在任何地方都有用吗,我目前正在学习 Java,所以想知道这在哪里有用。
  • 当你想从集合中删除一个对象时很有用(无论是队列还是任何集合)
  • 你有没有在排队等候餐厅或看电影,最后决定去别的地方?这就是您可能希望将其用于队列的原因之一。
  • 支持附加操作与队列概念并不矛盾。否则,连toString() 方法都不允许。

标签: java collections linked-list queue


【解决方案1】:

出于好奇,我研究了 LinkedList 对象和集合接口中的 remove 方法。 remove 函数的作用是遍历节点,找到对象,然后取消链接对象。

    public boolean remove(Object o) {
    if (o == null) {
        for (Node<E> x = first; x != null; x = x.next) {
            if (x.item == null) {
                unlink(x);
                return true;
            }
        }
    } else {
        for (Node<E> x = first; x != null; x = x.next) {
            if (o.equals(x.item)) {
                unlink(x);
                return true;
            }
        }
    }
    return false;
}

现在,unlink 方法基本上是对一个节点起作用,就像队列一样,左右迭代以找到该对象。 另外,请记住,这个对象有一个 modCount,它跟踪修改并实现快速失败行为(如果有什么东西是假的)

E unlink(Node<E> x) {
    // assert x != null;
    final E element = x.item;
    final Node<E> next = x.next;
    final Node<E> prev = x.prev;

    if (prev == null) {
        first = next;
    } else {
        prev.next = next;
        x.prev = null;
    }

    if (next == null) {
        last = prev;
    } else {
        next.prev = prev;
        x.next = null;
    }

    x.item = null;
    size--;
    modCount++;
    return element;
}

根本不是一个完整的答案,但是,您可以看到,它遍历节点。也许您可以通过书籍和教程来研究 Big O 和算法。然而,简单地说,LinkedList 是一种混合包,在这里和那里实现。 所以,FIFO会被保留,索引会一直被追踪,然而,除了切割头或尾节点之外,会遍历做remove。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-08-14
    • 1970-01-01
    • 2011-01-21
    • 2019-08-22
    • 1970-01-01
    • 2011-07-20
    • 2013-08-27
    相关资源
    最近更新 更多