1

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?

Buddy
  • 13
  • 3
  • To be more accurate the "searching to get to the right node" is O(N). If you've already got a pointer to the actual node you want to insert at, the actual creation of the new node and linking is O(1). – wLui155 Apr 22 '21 at 20:52
  • @wLui155, note that the OP says the inserted node will *precede* the current node. In a singly linked list you cannot do that in O(1). The searching is really a necessary part of the whole operation, as you search the node that precedes the given node. – trincot Apr 22 '21 at 20:56
  • Anyhow, Buddy, you got it right. – trincot Apr 22 '21 at 20:59
  • Good point, I misread the question. – wLui155 Apr 22 '21 at 21:02
  • @trincot it is possible in ```O(1)```, see my answer – Abhinav Mathur Apr 23 '21 at 04:33
  • @AbhinavMathur, we may say this takes O(*m*) complexity, where *m* is the (average) size of a node's data. Depends on whether this is allowed. Could be strange for the caller to see their node's data was altered. – trincot Apr 23 '21 at 06:11

1 Answers1

0

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.

Abhinav Mathur
  • 7,791
  • 3
  • 10
  • 24