It seems that the only Big-Oh behavior possible for adding something to a linked list would be O(N) since you must traverse the entire list. However from what I hear the overall number of operations should be no more than N/2. Can someone please explain how this is possible, as I see it if you traverse from both ends of the linked list the overall behavior will still be O(N). What am I missing?
Share
If you are asking why will inserting an element at an arbitrary position in a doubly linked list of length N always take at most O(N/2), that could be because if you always maintain a separate pointer/reference to the middle element and a count of the total number of elements, you will only need to traverse at most half the list to insert at a given position.
For example, say you have a list of
[B, C, D, E, F, G, H], if you have a pointer to theEelement and you know you have 7 items in your list. If you callinsert(0, A)to insert elementAat position0, then you’ll know that if you traverse 3 links backwards you’ll go from position 3 to position 0 (remember zero index is the first, so you go fromE@3 ->D@2 ->C@1 ->B@0). From there you can insert elementAbefore your ‘current’ element (B).Note that people normally leave constant terms out of big-O analysis; O(n/2) and O(n) have the same performance characteristics as
nincreases.