Question description Kapildev works in the mobile phone marketing industry. For example, if someone successfully answers this question, they will be given a mobile phone at a 50% discount. One of the competition's requirements was to write a C programme that swapped nodes for two specified keys in a linked list with two keys. By altering linkages, nodes should be switched. When data consists of several fields, swapping data across nodes might be costly. It is reasonable to presume that all keys in a linked list are unique. example : Given linked list : 10->15->12->13->20->14 and swap keys X=12 and Y=20. Linked list after swapping : 10->15->20->13->12->14 (if X or Y or Both are not present in Linked List, ABORT the Swapping)
C Program


#include<stdio.h>

#include<stdlib.h>

struct node

{

    int data;

    struct node *next;

};

void printList(struct node *head)

{

    printf("-->");

    while(head)

    {

        printf("%d",head->data);

        if(head->next) printf("-->");

        head=head->next;

    }

}

void swapNodes(struct node **head_ref, int x, int y)

{

    if(x==y) return;

    struct node *prevX=NULL,*currX=*head_ref;

    struct node *prevY=NULL,*currY=*head_ref;

    while(currX && currX->data!=x)

    {

        prevX=currX;

        currX=currX->next;

    }

    while(currY && currY->data!=y)

    {

        prevY=currY;

        currY=currY->next;

    }

    if(!currX || !currY) return;

    if(prevX)

        prevX->next=currY;

    else

        *head_ref=currY;

    if(prevY)

        prevY->next=currX;

    else

        *head_ref=currX;

    struct node *temp=currX->next;

    currX->next=currY->next;

    currY->next=temp;

}

int main()

{

    int n,i,val,x,y;

    struct node *head=NULL,*newnode;

    scanf("%d",&n);

    for(i=0;i<n;i++)

    {

        scanf("%d",&val);

        newnode=(struct node*)malloc(sizeof(struct node));

        newnode->data=val;

        newnode->next=head;

        head=newnode;

    }

    scanf("%d %d",&x,&y);

    printf("before Swapping:");

    printList(head);

    swapNodes(&head,x,y);

    printf("\nafter Swapping:");

    printList(head);

    return 0;

}