I have a Node
class to implement linked list:
class Node
{
public:
int data;
Node *next;
Node(int d){
data=d;
next=NULL;
}
};
And in a solution class I have methods to insert, removeDuplicates, print etc;
Now to removeDuplicates
my logic is:
- if my current's next node is null then return
- if current's value is equal to current's next's value then set next to current
- recurse with next
So here is my code:
Node* removeDuplicates(Node* head)
{
process(head);
return head;
}
void process(Node* node)
{
cout << node->data << endl;
if(node->next==NULL)
return;
if(node->data==node->next->data)
node=node->next;
process(node->next);
}
when I call removeDuplicate
method, it prints: 1 2 3 4
as expected, but after that when I again print with my another method, it gives me the whole linked list, without removing duplicates : 1 2 2 3 3 4
display
method:
void display(Node *head)
{
Node *start=head;
while(start)
{
cout<<start->data<<" ";
start=start->next;
}
}
Aucun commentaire:
Enregistrer un commentaire