I am done with insertion, search in circular linked list but for removal I am getting compiler errors...
Following is my structure for nodes.
struct node
{
int p_data;
struct node* p_next;
node(node* head, int data)
{
p_next = head;
p_data = data;
}
explicit node(int data)
{
p_next = nullptr;
p_data = data;
}
};
node* remove_circular(node* head, node* target)
{
if (head == target->p_next)
{
delete head;
return nullptr;
}
auto next_pointer = target->p_next;
target->p_data = next_pointer->p_data;
target->p_next = next_pointer->p_next;
delete target->p_next;
return target;
}
and in main function I call
head = remove_circular(head, head);
head = remove_circular(head, temp);
this is to remove head element and another element that temp points to. But I am getting errors
Anybody has any idea to remove one element from circular list??
I changed it to delete target->p_next; but now it deletes everything in the list. Any idea???
You need to consider several things.
1.) the case of an empty list
2.) The target to be removed is the head node and this is the only node in the list.
3.) Create a loop that iterates through the entire list. You have something that would only delete the next node which works if you have a two item list and target was the second item.
4.)Inside you loop add a check to see if the list has been traversed and target was never found.
5.) Inside the loop add the else case which means target was in an arbitrary location in the list. Since I gave you the rest I'll leave you to get this part. It's not hard just a few lines longer than the statements above.
This is how a circular linked list works:
Each node points to the next in line, and the tail of the list points to the header node. That's the difference from a
circular linked list
to aregular linked list
(which, in the case above, would make 37 point to a terminatornull
).In the case of your list having only one object, then it should look something like this:
So, as you can see, there is no object pointing to
null
anywhere, yet it happens on your code with yourexplicit
constructor (which will run if I writenode n = node(12)
).I suggest you take a look at this link to have a better understanding of how your algorithm should look like.
Once you resolve your compiler error, you are still going to have algorithmic issues. I suggest you draw a circular list on paper and think about the steps required to remove an element. Consider all the cases, for example: empty list, list of 1 item, element not in the list, etc.