Why is inserting in the middle of a linked list O(1)?

Rob Sobers picture Rob Sobers · May 8, 2009 · Viewed 53.1k times · Source

According to the Wikipedia article on linked lists, inserting in the middle of a linked list is considered O(1). I would think it would be O(n). Wouldn't you need to locate the node which could be near the end of the list?

Does this analysis not account for the finding of the node operation (though it is required) and just the insertion itself?

EDIT:

Linked lists have several advantages over arrays. Insertion of an element at a specific point of a list is a constant-time operation, whereas insertion in an array may require moving half of the elements, or more.

The above statement is a little misleading to me. Correct me if I'm wrong, but I think the conclusion should be:

Arrays:

  • Finding the point of insertion/deletion O(1)
  • Performing the insertion/deletion O(n)

Linked Lists:

  • Finding the point of insertion/deletion O(n)
  • Performing the insertion/deletion O(1)

I think the only time you wouldn't have to find the position is if you kept some sort of pointer to it (as with the head and the tail in some cases). So we can't flatly say that linked lists always beat arrays for insert/delete options.

Answer

CookieOfFortune picture CookieOfFortune · May 8, 2009

You are correct, the article considers "Indexing" as a separate operation. So insertion is itself O(1), but getting to that middle node is O(n).