HiveBrain v1.2.0
Get Started
← Back to all entries
patternMinor

What is the average time complexity, for a single linked list, for performing an insert?

Submitted by: @import:stackexchange-cs··
0
Viewed 0 times
performingtheinsertwhataveragetimesingleforlistlinked

Problem

I thought this would be a very simple O(n) b.c. you can do the insert any where with in the list.

The longer the list, the longer it will take on average to do the insert.

However according to bigocheatsheet it is O(1) or has no dependency on the size of the list.

What is wrong here?

Solution

Either if you want to insert at the end of the list or at the beginning of the list, you're going to have $O(1)$ Complexity for that and $O(1)$ space.
If you want to insert at the beginning of the list, you just make the new list head the node you want to insert, and link it to the previous list head.
If you want to insert at the end of the list, you can also hold the end of the list as a pointer and insert a new node after it.
If you want to insert in an arbitrary place in the list, then linearly going there is going to be the best you can do ( to my knowledge ).
Statistically you'll have to go through $(n+1)/2 $ nodes to get through yours.

Context

StackExchange Computer Science Q#48030, answer score: 7

Revisions (0)

No revisions yet.