Wednesday, 16 May 2012

Write a C program to generate a list and divide into two sublist one contating elements at odd index and other elements at even index.

Underlying concept to demonstrate: Self-referential structure, linked list.

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

struct node
{
        int data;
        struct node *next;
};
typedef struct node LL;


void display(LL *p)
{

        printf("\n The linked list is: ");

        while(p!=NULL)
        {
                printf(" %d",p->data);
                p=p->next;
        }
}

void insert(LL **head,int n)
{
        LL *temp,*current;
        temp=(LL *)malloc(sizeof(LL));
        temp->data=n;
        temp->next=NULL;
        if(*head==NULL)
                        *head=temp;
        else
                {
                        current=*head;
                        while(current->next!=NULL)
                                current=current->next;
                        current->next=temp;
                }
}


int main()
{
        LL *head,*odd,*even;
        head=NULL;
        odd=NULL;
        even=NULL;
        int num;
        printf("\n Linked list:\n");
        do
        {
                printf("\n Enter the no. to insert(Enter -ve to stop inserting):");
                scanf("%d",&num);
        if(num<0)
            break;
                insert(&head,num);
        }while(1);


        display(head);
        LL *temp;
    temp=head;
    int i=0;
    while(temp!=NULL)
    {
        i++;
        if(i%2==0)
            insert(&even,temp->data);
        else
                insert(&odd,temp->data);   
        temp=temp->next;
    }


    printf("\n Sub list with elements having odd index:");
    display(odd);
    printf("\n Sub list with elements having even index:");
    display(even);
    return 0;
}

0 comments

 
© 2011-2012 ProgrammingBlue
Posts RSS Comments RSS
Back to top