简体   繁体   中英

What is the running of following code if implement by ArrayList and LinkedList?

 for (int i =0; i < n; i++){
        lst.add(lst.size()/2,3*i);          
    }

I was thinking that the for loop will take o(n) but I was not clear what what the difference between add(j,t) if using ArrayList and LinkedList.. Thanks!

For inserting in the some slot k of an ArrayList , finding k is O(1), but then you're going to have to push back each element after k, which is O(n). However, inserting at the end of an ArrayList is amortized O(1), amortized since we need to factor in the situations when the array needs to be resized.

For a LinkedList , unless you have a reference to the element at position k, then you need to iterate through the list to find said position, which is O(n), whereas actually inserting is always O(1).

For LinkedList<E> :

add(int index, E element) is O(n)

For ArrayList<E> :

add(int index, E element) is O(n - index) amortized, but O(n) worst-case (as above)

Source:

https://stackoverflow.com/a/322742/2498729

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