What is the time complexity of a size() call on a LinkedList in Java?

后端 未结 2 920
谎友^
谎友^ 2020-12-13 23:52

As the title asks, I wonder if the size() method in the LinkedList class takes amortized O(1) time or O(n) time.

2条回答
  •  感动是毒
    2020-12-14 00:38

    O(1) as you would have found had you looked at the source code...

    From LinkedList:

    private transient int size = 0;
    

    ...

    /**
     * Returns the number of elements in this list.
     *
     * @return the number of elements in this list
     */
    public int size() {
       return size;
    }
    

提交回复
热议问题