I'm a CS student and I'm just started to learn about linked lists. I want to write the simplest code that deletes a node from a linked list, which means that I won't take into account any special cases; like what if the element is at the head or what if the element is in the last node or what if there were duplicate elements in (2 nodes containing the value 5 for instance) or any of that. So my question is fairly simple. What do I need to adjust in this small piece of code that I wrote. And can I get away with my usage of the arrows?
Thank you and have a nice day!
note: the result of this code was kinda strange. I had the below mentioned function inside of a loop along with other functions the other functions are working fine, but when I call the below mentioned function I'd just get an infinite loop requesting me to enter data as arguments to the function. I'm guessing it's the way I used the arrows? if it's not then I'll just adjust this question and post the whole code if that's needed. it's just that my code is like 200 lines so I didn't want to post it as a whole.
`node* deleteFromList (node* head, int x)
{
node* tmp = head ;
while(tmp->next->data != x );
{
tmp = tmp->next;
}
tmp->next= tmp->next->next;
free (tmp->next);
return head;
}`
tmp->next= tmp->next->next;
free (tmp->next);
You set tmp->next
to point to the node you want to keep. Then you free tmp->next
, freeing the node you wanted to keep.