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;
}
0 Comments