代码之家  ›  专栏  ›  技术社区  ›  Mark McDonald

Java中的LIKEDList.GETLAST()的时间复杂度是多少?

  •  14
  • Mark McDonald  · 技术社区  · 14 年前

    我在Java类中有一个私有链接列表,经常需要检索列表中的最后一个元素。列表需要缩放,因此我正在尝试决定在进行更改(实现o(1))时是否需要保留对最后一个元素的引用,或者LinkedList类是否已经使用getLast()调用进行了此操作。

    LinkedList.GetLast()的最大成本是多少? 是否记录在案? (也就是说,我是否可以依赖这个答案,或者我是否应该不做任何假设并缓存它,即使它是O(1)?

    5 回复  |  直到 14 年前
        1
  •  26
  •   Matt    14 年前

    它是O(1),因为列表是双重链接的。它保持对头部和尾部的引用。

    来自文档:

    索引到列表中的操作将从开始或结束遍历列表,以更接近指定索引的为准。

        2
  •  5
  •   Jeff Storey    14 年前

    它是O(1),您不必缓存它。getlast方法只返回 header.previous.element ,所以没有计算,也没有遍历列表。当需要在中间查找元素时,链接列表会变慢,因为它从一端开始,一次移动一个元素。

        3
  •  2
  •   Yaneeve    14 年前

    来自Java 6的源代码:

    * @author  Josh Bloch
     * @version 1.67, 04/21/06
     * @see     List
     * @see     ArrayList
     * @see     Vector
     * @since 1.2
     * @param <E> the type of elements held in this collection
     */
    
    public class LinkedList<E>
        extends AbstractSequentialList<E>
        implements List<E>, Deque<E>, Cloneable, java.io.Serializable
    {
        private transient Entry<E> header = new Entry<E>(null, null, null);
        private transient int size = 0;
    
        /**
         * Constructs an empty list.
         */
        public LinkedList() {
            header.next = header.previous = header;
        }
    
    ...
    
        /**
         * Returns the first element in this list.
         *
         * @return the first element in this list
         * @throws NoSuchElementException if this list is empty
         */
        public E getFirst() {
        if (size==0)
            throw new NoSuchElementException();
    
        return header.next.element;
        }
    
        /**
         * Returns the last element in this list.
         *
         * @return the last element in this list
         * @throws NoSuchElementException if this list is empty
         */
        public E getLast()  {
        if (size==0)
            throw new NoSuchElementException();
    
        return header.previous.element;
        }
    
    ...
    
    }
    

    所以这两个都是O(1) getFirst() 和; getLast()

        4
  •  1
  •   Bill the Lizard    14 年前

    LinkedList 文档:

    对于双重链接列表,所有操作都按预期执行。索引到列表中的操作将从开始或结束遍历列表,以更接近指定索引的为准。

    它应该是O(1),因为一个双重链接的列表将有一个对它自己的尾部的引用。(即使没有 明确地 参照它的尾巴,它将是o(1)到 找到 它的尾巴)

        5
  •  0
  •   Eyal Schneider    14 年前

    linkedlist.getlast()的实现毫无疑问—它是一个O(1)操作。 但是,我没有发现它记录在任何地方。