简体   繁体   中英

Time complexity to insert a node before the node pointed by some pointer in circular singly list of n nodes?

I think that it is O(N) because in a circular singly list the pointer visits n nodes so that node to be inserted precedes the current node.

Have I got it right?

The usual traversal and insertion would take O(N) time. However, it can be done in O(1) as well, if the nodes can be modified.
Let the list look like A -> B-> C -> D -> A , we are given a pointer to C , and we have to insert E . Now, create a copy of C and insert it after C itself. The list now looks like A -> B-> C -> C(copy) -> D -> A . Now, we can modify the values of the original C node to store the values of E node, so the list now becomes A -> B-> E -> C -> D -> A . Since you've only created a node and inserted it in place, it takes O(1) time complexity.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM