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

家住魔仙堡 提交于 2019-11-27 11:53:56

问题


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


回答1:


It's O(1). You can google for the source code and you will come to such:

From http://www.docjar.com/html/api/java/util/LinkedList.java.html

All of the Collection classes I have looked at store a the size as a variable and don't iterate through everything to get it.




回答2:


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;
}


来源:https://stackoverflow.com/questions/863469/what-is-the-time-complexity-of-a-size-call-on-a-linkedlist-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!