Friday 30 December 2016

Sorting data in linked list



Suppose the Personnel file of a small company contain the following data for all its employees SSN(social security number),Name and salary. A Linked list is used to store the Ask students to write a function to sort the records based on SSN?
 

#include <stdio.h>
#include <string.h>
struct node
{
    int ssn,sal;
    char name[50];
    struct node *next;
};
struct node *head=NULL,*c,*p;
void create()
{
    int value,s;
    char n[50];
    printf("enter SSN, name and sal");
    scanf("%d%s%d",&value,n, &s);
    struct node * new = (struct node *)malloc(sizeof(struct node));
    new->next=NULL;
    new->ssn=value;
    strcpy(new->name,n);
    new->sal=s;
    if(head == NULL)
        head = new;
    else
    {
        c=head;
        while(c->next != NULL)
        {
            c=c->next;
        }
        c->next=new;
    }
}
display()
{
    if(head == NULL)
        printf("list is empty");
    else
        {
            c=head;
            while(c->next!=NULL)
            {
                printf("\n%d\t%s\t%d\n",c->ssn,c->name,c->sal);
                c=c->next;
            }

                printf("\n%d\t%s\t%d\n",c->ssn,c->name,c->sal);
        }
}
main()
{
    int n,i,temp,j,t1,t2;
    char ntemp[50];
    printf("enter the number of records");
    scanf("%d",&n);
    for(i=0;i<n;i++)
            create();
        //    display();
    c=head;
    for(c=head;c->next != NULL;c=c->next)
    {
        for(p=c->next;p!=NULL;p=p->next)
        {
            if(c->ssn > p->ssn)
            {
                t1=c->ssn;t2=c->sal;strcpy(ntemp,c->name);
                c->ssn=p->ssn;c->sal=p->sal;strcpy(c->name,p->name);
                p->ssn=t1;p->sal=t2;strcpy(p->name,ntemp);
            }
           
        }
    }
    display();
}

No comments:

Post a Comment