Tuesday, 9 October 2012

SWAP THE NODE


Written exam (Amazon, Bangalore)

Given a singly link list and a number 'K', swap the Kth node from the start with the Kth node from the last. Check all the edge cases.

Sample Input: 1->2->3->4->5->6->7->8 and K = 3
Sample Output : 1->2->6->4->5->3->7->8


SOLUTION USING DOUBLY LINK LIST


#include
#include
int main()
{
    struct node
    {
        int data;
        struct node *next;
        struct node *prev;
    }*head;
    int num,i,k,c,n;
    struct node *temp,*temp1,*temp2,*temp3,*end;
    printf("enter number of link list");
    scanf("%d",&num);
    scanf("%d",&k);
    head=NULL;
    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;
    temp1=end;
    temp=head;
    for(i=1;i<=num;i++)
    {
        if(i==k)
        {
            int c=temp->data;
            temp->data=temp1->data;
            temp1->data=c;
        }
        else
        {
            temp=temp->next;
            temp1=temp1->prev;
        }
    }
    temp=head;
    while(temp!=NULL)
    {
        printf("%d ",temp->data);
        temp=temp->next;
    }
    return 0;
}

SOLUTION USING SINGLE LINK LIST


#include  
#include
int main()
{
    struct node
    {
        int data;
        struct node *next;
    }*head;
    head=NULL;
    int i,num,k,n;
    struct node *temp,*temp1,*temp2;
    printf("enter the number=");
    scanf("%d",&num);
    scanf("%d",&k);
    for(i=1;i<=num;i++)
    {
        scanf("%d",&n);
        if(head==NULL)
        {
            head=malloc(sizeof(struct node));
            head->data=n;
            temp=head;
        }
        else
        {
            temp->next=malloc(sizeof(struct node));
            temp->next->data=n;
            temp=temp->next;
        }
    }
    temp->next=NULL;
    temp=head;
    i=1;
    while(temp!=NULL)
    {
        if(i==k)
        {
            temp1=temp;
            temp=temp->next;
        }
        else if(i==num-k-1)
        {
            temp2=temp;
            temp=temp->next;
        }
        else
        {
            temp=temp->next;
        }
        i=i+1;
    }
    temp=temp1;
    int c=temp->data;
    temp=temp2;
    int d=temp->data;
    temp=temp1;
    temp->data=d;
    temp=temp2;
    temp->data=c;
    temp=head;
    while(temp!=NULL)
    {
        printf("%d ",temp->data);
        temp=temp->next;
    }
    return 0;
}



No comments: