Wednesday, 12 March 2014

Define a self referential structure for representing a simple linked list of integers. Write a C function to split the list into two lists so that the first list contains all even numbered elements and the second list contains only odd numbered elements. For example, if the original list is {2, 8, 1, 13, 14, 28, 0} then the resultant list first list would be {2, 8, 14, 28, 0} and the second list would be { 1, 13}.

#include<stdio.h>
#include<malloc.h>
struct node
{
    int info;
    struct node *link;
};

void create_list(struct node **start,int data)
{
    struct node *q,*tmp;
    tmp= malloc(sizeof(struct node));
    tmp->info=data;
    tmp->link=NULL;
    if(*start==NULL)
        *start=tmp;
    else
    {
        q=(*start);
        while(q->link!=NULL)
        {
            q=q->link;
        }
        q->link=tmp;
    }
}

void display(struct node *start)
{
    struct node *q;
    if(start==NULL)
    {
        printf("List is empty\n");
        return;
    }
    q=start;
   
    while(q!=NULL)
    {
        printf("%d ", q->info);
        q=q->link;
    }
    printf("\n");
}

void split_list(struct node *start,struct node **even,struct node **odd)
{
    struct node *q;
    q=start;
    while(q!=NULL)
    {
        if(q->info%2==0)
        {
            create_list(&(*even),q->info);
        }
        else
            create_list(&(*odd),q->info);       
        q=q->link;
    }   
}

main()
{
    struct node *start=NULL,*even=NULL,*odd=NULL;
    int n,i,m;
    printf("Number of terms of 1st list ");
    scanf("%d",&n);
    for(i=0;i<n;i++)
    {
        printf("Enter the element : ");
        scanf("%d",&m);
        create_list(&start,m);
    }
    printf("List is :\n");
    display(start);
    split_list(start,&even,&odd);
    printf("Even List is :\n");
    display(even);
    printf("Odd List is :\n");
    display(odd);
}

No comments:

Post a Comment