ringa_lee2017-04-17 11:22:53
I agree with brayden's statement above. This question has no meaning in terms of data structure and algorithm. It should be that the poster read the question wrongly. The problem is that it takes O(1) time to delete a node in a circular singly linked list. The following is a simple solution to delete a node in a circular singly linked list in O(1) time:
Assume that the node to be deleted is ListNode *toBeDeleted
If deletion is required in O(1) time, traversal cannot be used. Since it is a single-linked list, the previous node of the node cannot be found without traversal, so the conventional linked list deletion method cannot be used.
Since we know the node ListNode *toBeDeleted
to be deleted, we can directly get its next node ListNode *pNext
. We can overwrite the pNext
node with the content of toBeDeleted
, then link the node toBeDeleted
to the next node of pNext
and then delete the pNext
node. The following is a simple diagram (assuming i is to be deleted):
The principle is very simple: completely clone the next node, and then delete the next node to achieve the illusion of deleting this node.
阿神2017-04-17 11:22:53
I have used similar data structures before, so there is no need to write any memory allocation function. The main implementation ideas are as follows:
But the main problem with this is: if the node contains resources, then the resources will inevitably be leaked.