Click here to hide categories Click here to show left categories

User: Home          welcome : Guest          Log In / Register here     




PROGRAM TO SWAP NODES IN LINEAR LINKED LIST

Download Attachment
/*********************************************/
/*PROGRAM TO SWAP NODES IN LINEAR LINKED LIST*/
/*********************************************/

#include < stdio.h>
#include < conio.h>
#include < malloc.h>
#include < process.h>
#include < ctype.h>

struct linear_list
{
    int info;
    struct linear_list *next;
}*start,*newnode,*ptr,*ptr1,*pt2;

void main()
{
    int item,loc,loc1,temp;
int i,j;
    char ch;
    clrscr();
    newnode=(struct linear_list*)malloc(sizeof(struct linear_list));
    start=newnode;
    do
    {
        printf("\nEnter data: ");
        scanf("%d",&item);
        newnode->info=item;
        printf("\nDo you want to create another node:(y/n)");
        fflush(stdin);
        scanf("%c",&ch);
        if(tolower(ch)=='y')
        {
newnode->next=(struct linear_list*)malloc(sizeof(struct linear_list));
            newnode=newnode->next;
        }
        else
        {
            newnode->next=NULL;
        }
    }while(tolower(ch)!='n');

    printf(“\n Linked List is:\n”);
    ptr=start;
    i=1;
    while(ptr!=NULL)
    {
        printf("\nNode %d : %d",i,ptr->info);
        ptr=ptr->next;
        i++;
    }

printf("\nEnter the locations of nodes whose values are tobe swapped:\n");
    printf("\nLocation 1: ");
    scanf("%d",&loc);
    printf("\nLocation 2: ");
    scanf("%d",&loc1);
    
    ptr1=start;
    ptr2=start;
    j=1;
    while(j!=loc1)
    {
        ptr1=ptr1->next;
        j=j+1;
    }
    j=1;
    while(j!=loc2)
    {
        ptr2=ptr2->next;
        j=j+1;
    }
    temp=ptr1->info;
    ptr1->info=ptr2->info;
    ptr2->info=temp;
    
printf(“\n After Swapping Linked List is:\n”);
    ptr=start;
    i=1;
    while(ptr!=NULL)
    {
        printf("\nNode %d : %d",i,ptr->info);
        ptr=ptr->next;
        i++;
    }

    getch();
}
 

Share this article   |    Print    |    Article read by 3255 times
Author:
Rohit kakria
I am software developer
Related Articles:
Related Interview Questions: No related interview question