Why is deleting in a single linked list O(1)?

后端 未结 8 2451
悲哀的现实
悲哀的现实 2020-12-25 14:50

I do not quiet understand why deleting at the end of a single linked list goes in O(1) time, as the wikipedia article says.

A single linked list consists out of node

8条回答
  •  伪装坚强ぢ
    2020-12-25 15:13

    If you're including the cost of fixing the dangling node, you can still do it in O(1) with the use of sentinel node for the end (also described on that page).

    Your "empty" list starts with a single sentinel

    Head -> [Sentinel]
    

    Add some stuff

    Head -> 1 -> 2 -> 3 -> [Sentinel] 
    

    Now delete the tail (3) by marking the node that was 3 as invalid, and then removing the link to the old sentinel, and freeing the memory for it:

    Head -> 1 -> 2 -> 3 -> [Sentinel] 
    Head -> 1 -> 2 -> [Sentinel] -> [Sentinel] 
    Head -> 1 -> 2 -> [Sentinel]
    

提交回复
热议问题