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

后端 未结 5 684
伪装坚强ぢ
伪装坚强ぢ 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条回答
  •  庸人自扰
    2020-12-17 15:42

    It is O(1) and you should not have to cache it. The getLast method simply returns header.previous.element, so there is no computation and no traversal of the list. A linked list slows down when you need to find elements in the middle it since it starts one end and moves one element at a time.

提交回复
热议问题