Thursday, September 15, 2016

C code to remove duplicate from a linked list

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

struct node
{
int data;
struct node *next;
};
struct node *start=NULL;
struct node *temp=NULL;

void insert()
{
int lData=0;
struct node *temp1;
printf("Please enter data:\t");
scanf("%d",&lData);
temp=malloc(sizeof(struct node));
temp1=start;
if(temp1 == NULL )
{
start=temp;
temp->data=lData;
temp->next=NULL;
}
else
{
printf("here1\n");
while(temp1->next != NULL)
{
temp1=temp1->next;
}
temp1->next=temp;
temp->data=lData;
temp->next=NULL;

}
}
void display()
{
struct node *temp1=start;
if(temp1 == NULL )
printf("Linked list is empty\n");
else
{
while(temp1->next != NULL )
{
printf("Final Element is [%d]\n",temp1->data);
temp1=temp1->next;
}
printf("Final Element is [%d]\n",temp1->data);
}
}
void remove_dup()
{
struct node *temp=start;
struct node *temp1=start->next;
struct node *temp2=start->next;
struct node *prev=NULL;
while(temp !=NULL)
{
prev=temp;
while(temp1 != NULL)
{
if(temp->data == temp1->data)
{
printf("going to remove [%d] [%d]\n",temp->data,prev->data);
prev->next=temp1->next;
temp2=temp1;
temp1=temp1->next;
free(temp2);
}
else
{
prev=temp1;
temp1=temp1->next;
}
}
temp=temp->next;
if(temp != NULL)
{
temp1=temp->next;
}
}
free(temp1);
}
int main()
{
int choice;
while(1)
{
printf(" 1. For Insert into link list\n 2. remove duplicates \n 3. Display link list\n 4. Exit\n\n Enter your choice:\t");
scanf("%d",&choice);
switch(choice)
{
case 1:
insert();
break;
case 2:
remove_dup();
break;
case 3:
display();
break;
case 4:
exit(0);
break;
default:
printf("Invalid choice\n");
break;
}
}
return 0;
}

No comments:

Post a Comment