What is the time complexity of LinkedList.getLast() in Java?

后端 未结 5 694
伪装坚强ぢ
伪装坚强ぢ 2020-12-17 15:06

I have a private LinkedList in a Java class & will frequently need to retrieve the last element in the list. The lists need to scale, so I\'m trying to decide whether I

5条回答
  •  猫巷女王i
    2020-12-17 15:44

    From the Java 6 source code:

    * @author  Josh Bloch
     * @version 1.67, 04/21/06
     * @see     List
     * @see     ArrayList
     * @see     Vector
     * @since 1.2
     * @param  the type of elements held in this collection
     */
    
    public class LinkedList
        extends AbstractSequentialList
        implements List, Deque, Cloneable, java.io.Serializable
    {
        private transient Entry header = new Entry(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;
        }
    
    ...
    
    }
    

    so that's O(1) for both getFirst() & getLast()

提交回复
热议问题