C code for removing duplicate nodes in linked list


linked list implementation in C
//removing duplicate elements without sorting
//using two loops
#include<stdio.h>
#include<malloc.h>
void insert(int d);
void display();
void deletee();
void reverse();
void removeDup();
struct node
{
int data;
struct node *next;
};
struct node *start;

int main()
{
printf("\n\n");
start=NULL;//starting with empty list
insert(10);
insert(10);
insert(10);
insert(15);
insert(15);
insert(15);
insert(23);
insert(15);
insert(23);
insert(15);
insert(77);
insert(99);
insert(99);
insert(99);
printf("\ndisplay() called:\n");
display();
printf("\n\n");

printf("\nremoveDup() called:\n");
removeDup();
display();
printf("\n\n");

printf("\ndeletee() called\n");
deletee();
display();
printf("\n\n");

printf("\nreverse() called\n");
reverse();
display();
printf("\n\n");

return 0;
}

void insert(int d)
{
struct node *newnode=(struct node*)malloc(sizeof(struct node));
newnode->data=d;
newnode->next=start;
start=newnode;
}
void display()
{
struct node *ptr=start;
while(ptr!=NULL)
{
printf("%d ",ptr->data);
ptr=ptr->next;
}
}
void deletee()
{
struct node *temp=(struct node*)malloc(sizeof(struct node));
temp=start;
start=start->next;
if(temp!=NULL)
{
free(temp);
}
}

void reverse()
{
struct node *next=(struct node*)malloc(sizeof(struct node));
struct node *result=(struct node*)malloc(sizeof(struct node));
struct node *current=(struct node*)malloc(sizeof(struct node));
next=NULL;
result=NULL;
current=start;
while(current!=NULL)
{
next=current->next;
current->next=result;
result=current;
current=next;
}
start=result;
}


void removeDup()
{
struct node *current=(struct node*)malloc(sizeof(struct node));
current=start;
struct node *temp=(struct node*)malloc(sizeof(struct node));
temp=NULL;
struct node *ptr1, *ptr2;
ptr1=start;
while(ptr1!=NULL )//&& ptr1->next!=NULL)
{
ptr2=ptr1;
while(ptr2->next!=NULL)//->next!=NULL)
{
if(ptr1->data==ptr2->next->data)
{
temp=ptr2->next;
ptr2->next=ptr2->next->next;
free(temp);
}
else
{
ptr2=ptr2->next;
}
}
ptr1=ptr1->next;
}
}
/*

display() called:
99 99 99 77 15 23 15 23 15 15 15 10 10 10


removeDup() called:
99 77 15 23 10


deletee() called
77 15 23 10


reverse() called
10 23 15 77


*/

No comments:

Post a Comment