Wednesday, 10 October 2012

ARRANGE THE LINK LIST


input linked list is : 1->9->3->8->5->7->7

do you see any pattern in this input ?

odd placed nodes are in increasing order and even placed nodes are in decreasing order.
write a code that gives the the following linkedlist:
output linked list should be 1->3->5->7->7->8->9  

SOLUTION USING DOUBLY LINK LIST--
#include
#include
int main()
{
    struct node
    {
        int data;
        struct node *prev;
        struct node *next;
    }*head;
    struct node *temp,*end,*temp1;
    head=NULL;
    int num,n,i;
    printf("enter nodes n link lis=");
    scanf("%d",&num);
    for(i=1;i<=num;i++)
    {
        scanf("%d",&n);
        if(head==NULL)
        {
            head=malloc(sizeof(struct node));
            head->data=n;
            temp=head;
            temp->prev=NULL;
        }
        else
        {
            temp->next=malloc(sizeof(struct node));
            temp->next->prev=temp;
            temp->next->data=n;
            temp=temp->next;
        }
    }
    temp->next=NULL;
    end=temp;
    temp=head;
    i=1;
    while(temp!=NULL)
    {
        if(i%2!=0){
        printf("%d ",temp->data);
        }
        temp=temp->next;
        i=i+1;
    }
    temp1=end;
    i=num;
    while(temp1!=NULL)
    {
        if(i%2==0){
        printf("%d ",temp1->data);
        }
        temp1=temp1->prev;
        i=i-1;
    }
    return 0;
}


USING SINGLE LINK LIST----

 link all odd nodes one after other and reverse all even nodes while traversing for odd nodes. Finally link tha last odd node with the last even node;

No comments: