Remove duplicates from an unsorted linked list
time complexity O(n)
#include<stdio.h>
#include<stdlib.h>
#include<set>
struct node
{
char data;
struct node *next;
}*head;
void insert(int num)
{
struct node* temp;
temp=(struct node *)malloc(sizeof(struct node));
temp->data=num;
temp->next=NULL;
if(head==NULL)
{
head=temp;
}
else
{
struct node* temp1=head;
while(temp1->next!=NULL)
{
temp1=temp1->next;
}
temp1->next=temp;
}
}
void display()
{
struct node *temp2;
temp2=head;
while(temp2!=NULL)
{
printf("%d ",temp2->data);
temp2=temp2->next;
}
}
void remove_the_duplicate_elements_from_the_linked_list()
{
struct node* temp=head;
struct node* prev=NULL;
std::set<int> checklist;
std::set<int>::iterator it;
while(temp!=NULL)
{
if(checklist.find(temp->data)==checklist.end())
{
checklist.insert(temp->data);
prev=temp;
}
else
{
if(checklist.find(temp->data)!=checklist.end())
{
prev->next=temp->next;
free(temp);
}
}
temp=temp->next;
}
}
int main()
{
int i,num;
int pos;
int n1,n2;
struct node *n;
head=NULL;
while(1)
{
printf("\nList Operations\n");
printf("===============\n");
printf("1.Insert\n");
printf("2.Display\n");
printf("3. Delete the duplicate elements from a linked list\n");
printf("4.Exit\n");
printf("Enter your choice : ");
if(scanf("%d",&i)<=0){
printf("Enter only an Integer\n");
exit(0);
} else {
switch(i)
{
case 1: printf("Enter the number to insert : ");
scanf("%d",&num);
insert(num);
break;
case 2: if(head==NULL)
{
printf("List is Empty\n");
}
else
{
printf("Element(s) in the list are : ");
}
display();
break;
case 3:
if(head==NULL)
{
printf("List is Empty\n");
}
else
{
printf("Deleting the duplicate elements from the linked list\n");
remove_the_duplicate_elements_from_the_linked_list();
printf("Elements removed\n");
}
break;
case 4:
return 0;
default: printf("Invalid option\n");
}
}
}
}
No comments:
Post a Comment