Insertion in the middle of ArrayList vs LinkedList

This question already has an answer here:

  • When to use LinkedList over ArrayList? 28 answers

  • The reason here is that there's no actual shifting of elements in the linked list. A linked list is built up from nodes, each of which holds an element and a pointer to the next node. To insert an element into a list requires only a few things:

  • create a new node to hold the element;
  • set the next pointer of the previous node to the new node;
  • set the next pointer of the new node to the next element in the list.
  • If you've ever made a chain of paper clips, you can think of each paper clip as being the beginning of the chain of it and all the paper clips that come after it. To stick a new paper clip into the chain, you only need to disconnect the paper clips at the spot where the new one will go, and insert the new one. A LinkedList is like a paper clip chain.

    An ArrayList is kind of like a pillbox or a mancala board where each compartment can hold only a single item. If you want to insert a new one in the middle (and keep all the elements in the same order), you're going to have to shift everything after that spot.

    The insertion after a given node in a linked list is constant time, as long as you already have a reference to that node (with a ListIterator in Java), and getting to that position will typically require time linear in the position of the node. That is, to get to the _n_th node takes n steps. In an array list (or array, or any structure that's based on contiguous memory, really) the address of the _n_th element in the list is just (address of 1st element)+n×(size of element), a trivial bit of arithmetic, and our compuring devices support quick access to arbitrary memory addresses.


    I think, when analysing the complexity, you need to take into account the metric you are using. In the ArrayList , your metric is shuffling , which is just assignment. But this is quite a complex operation.

    On the other hand, you're using a LinkedList , and you're simply looking going to the reference. In fact, you only perform 1 insertion. So while the algorithmic complexity will wind up similar, the actual processes that are being executed at O(n) time are different. In the case of an ArrayList , it is performing a lot of memory manipulation. In the case of a LinkedList , it's only reading.

    For those saying he doesn't understand LinkedLists

    A LinkedList only has a pointed at the start, and a pointer at the end. It does not automatically know the Node behind the node you want to delete (unless it's a doubly linked list) so you need to traverse through the list, from the start by creating a temp pointer, until you come to the node before the one you want to delete, and I believe it's this that OP is discussing.

    链接地址: http://www.djcxy.com/p/19964.html

    上一篇: LinkedList和ArrayList实现的区别?

    下一篇: 插入ArrayList vs LinkedList中间