Program for Sorting the Linked List and Removing Duplicates in C

#include<stdio.h>
struct node
 {
  int data;
  struct node *next;
 } *head,*temp,*temp1;
void create();
void sort();
void rem();
void print();
void main()
 {
   create();
   printf("\nElements in the entered list:\n");
   print();
   sort();
   rem();
   printf("\nElements after removing Duplicates:\n");
   print();
 }
/*Create function is used to create linked list, read the elements from the user and store them in the created linked list*/
void create()
 {
   int num;
   printf("\nEnter element or enter -1 to exit\n");
   head=(struct node*)malloc(sizeof(struct node));
   scanf("%d",&num);
   if(num==-1)
     {
      head=NULL;
     }
   else
     {
       head->data=num;
       head->next=NULL;
     }
   while(head!=NULL)
     {
       printf("\nEnter element or enter -1 to exit\n");
       scanf("%d",&num);
       if(num==-1)
{
         break;
        }
       else
{
       temp=head;
       while(temp->next!=NULL)
      {
       temp=temp->next;
      }
       temp1=(struct node*)malloc(sizeof(struct node));
      temp1->data=num;
      temp1->next=NULL;
      temp->next=temp1;
}
   }
 }
/*Sort function is used to sort the elements of linked list in ascending order*/
void sort()
 {
  struct node *ptr,*ptr1;
  int k;
  for(ptr=head;ptr!=NULL;ptr=ptr->next)
    {
      for(ptr1=ptr;ptr1!=NULL;ptr1=ptr1->next)
{
if((ptr->data)>ptr1->data)
  {
    k=ptr->data;
    ptr->data=ptr1->data;
    ptr1->data=k;
  }
}
 }
}
/*rem Function is used to remove the duplicate elements from the sorted linked list*/
void rem()
 {
  struct node *dup;
  for(temp=head;temp!=NULL;temp=temp->next)
    {
     if(temp->data==temp->next->data)
      {
       dup=temp->next;
       temp->next=temp->next->next;
       free(dup);
      }
    }
 }
/*Print function is used to print the elements in linked list*/
 void print()
 {
   struct node *head1=head;
   while(head1!=NULL)
    {
     printf("%d\t",head1->data);
     head1=head1->next;
    }
 }

Frenzz execute this program with different inputs.........
Share on Google Plus
    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment