简体   繁体   中英

Time Complexity while deleting last element from arraylist and linkedlist

1st Part :-

I was reading in the book - "Data Structure and Algorithms made easy in Java" that the time complexity for deleting the last element from Linkedlist and Arraylist is O(n). But the Linkedlist internally implements DoublyLinkedlist so the time complexity should be O(1) and similarly for Arraylist as it internally implement Array it should be O(1).

2nd Part :-

It also says that the insertion of an element at the ending of a linkedlist has a time complexity of O(n) but the linkedlist maintains pointers both at the end and at the front. So it this statement correct ? Moreover it says that the time complexity to insert an element in an arraylist at the end is O(1) if array is not full and O(n) if the array is full. Why O(n) if the array is full ?

Thanks for answering the 1st part . Can anyone please also explain the 2nd part. Thanks :)

It depends on what methods you're calling.

A glance at the implementation shows that if you're calling LinkedList.removeLast() , that's O(1). The LinkedList maintains pointers both to the first and last node in the list. So it doesn't have to traverse the list to get to the last node.

Calling LinkedList.remove(index) with the index of the last element is also O(1), because it traverses the list from the closest end. [Noted by user @andreas in comment below.]

But if you're calling LinkedList.remove(Object) , then there's an O(n) search for the first matching node.

Similarly, for ArrayList, if you're calling ArrayList.remove(index) with the index of the last element, then that's O(1). For all other indices, there's a System.arrayCopy() call that can be O(n) -- but that's skipped entirely for the last element.

But if you call ArrayList.remove(Object) , then again there's an O(n) search for the first matching node.

Removing last element of a linked list will take O(n) if it has to traverse all the records to reach the end. But implementation of java.util.LinkedList which is doubly-linked , does not keep reference only to head, but also keeps a reference of tail and allows you to remove last in O(1). It is implemented in a clever way to traverse the list from the beginning or the end, whichever is closer to the specified index

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM