#include <iostream>
using namespace std;
class ListNode
{
public:
int item;
ListNode* next;
};
void deleteDuplicates(ListNode * list)
{
ListNode* currentNode = list;
ListNode* next_next;
if (currentNode == NULL)
return;
while (currentNode->next != NULL)
{
if (currentNode->item == currentNode->next->item)
{
next_next = currentNode->next->next;
free(currentNode->next);
currentNode->next = next_next;
}
else
{
currentNode = currentNode->next;
}
}
}
void add(ListNode** head, int data)
{
ListNode* node = new ListNode();
node->item = data;
node->next = (*head);
(*head) = node;
}
void displayList(ListNode *node)
{
while (node!=NULL)
{
cout<<" "<<node->item<<" ";
node = node->next;
}
}
int main()
{
ListNode* list = NULL;
add(&list, 1);
add(&list, 13);
add(&list, 13);
add(&list, 1);
add(&list, 11);
add(&list, 12);
cout<<"The original linked list with duplicates:\n ";
displayList(list);
deleteDuplicates(list);
cout<<"\nThe new linked list after removing duplicates:\n";
displayList(list);
return 0;
}
Comments
Leave a comment