Below program is used to remove the duplicates from a sorted singly linked list. The code gives garbage values in online IDE. But when I comment the line .
delete curr;
The program works fine in online IDE itself. Here is the function I wrote. The other parts of the code are well-defined(not by me) by the online Judge.
And also the code without commenting the line delete curr; works fine in local IDE(codeblocks).
FULL PROGRAM:http://ideone.com/9bHab0
Why do I get the garbage values?
Node *removeDuplicates(Node *root)
{
// your code goes here
struct Node* curr = root,*prev = NULL;
while(curr)
{
if(prev==NULL)
prev = curr;
else if(curr->data!=prev->data)
prev = curr;
else
{
prev->next = curr->next;
delete curr;
curr = prev->next;
}
}
return root;
}
EDIT: One could see the pointer whose location is deleted, is reassigned immediately. Thus there couldn't be a dangling pointer here!