[英]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.我认为它是 O(N) ,因为在循环单个列表中,指针访问 n 个节点,以便要插入的节点在当前节点之前。
Have I got it right?我做对了吗?
The usual traversal and insertion would take O(N)
time.通常的遍历和插入将花费
O(N)
时间。 However, it can be done in O(1)
as well, if the nodes can be modified.但是,如果可以修改节点,也可以在
O(1)
中完成。
Let the list look like A -> B-> C -> D -> A
, we are given a pointer to C
, and we have to insert E
.让列表看起来像
A -> B-> C -> D -> A
,我们得到一个指向C
的指针,我们必须插入E
。 Now, create a copy of C
and insert it after C
itself.现在,创建
C
的副本并将其插入到C
本身之后。 The list now looks like A -> B-> C -> C(copy) -> D -> A
.该列表现在看起来像
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
.现在,我们可以修改原来的
C
节点的值来存储E
节点的值,所以列表现在变为A -> B-> E -> C -> D -> A
。 Since you've only created a node and inserted it in place, it takes O(1)
time complexity.由于您只创建了一个节点并将其插入到位,因此需要
O(1)
时间复杂度。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.