#include<stdio.h>
// Structure of Node
struct node
{
int data;
struct node *next;
};
typedef struct node node;
//Function to insert data in linked list
void insert(node **ptr,int val)
{
node *nn=(node*)malloc(sizeof(node));
nn->data=val;
nn->next=*ptr;
/*Move start Pointer to head*/
*ptr=nn;
}
//Function to print linked list
void printList(node *ptr)
{
while(ptr!=NULL)
{
printf("%d ",ptr->data);
ptr=ptr->next;
}
}
//Function to swap nodes
void swapNode(node **head,int val_1,int val_2)
{
//If both values are same nothing to do
if(val_1==val_2)
return;
//Search for val_1
node *ptr_1=*head,*prev_1=NULL;
while(ptr_1 && ptr_1->data!=val_1)
{
prev_1=ptr_1;
ptr_1=ptr_1->next;
}
//Search for val_2
node *ptr_2=*head,*prev_2=NULL;
while(ptr_2 && ptr_2->data!=val_2)
{
prev_2=ptr_2;
ptr_2=ptr_2->next;
}
//Value not found
if(ptr_2==NULL || ptr_1==NULL)
return;
if(prev_1!=NULL)
prev_1->next=ptr_2;
else
*head==ptr_2;
if(prev_2!=NULL)
prev_2->next=ptr_1;
else
*head=ptr_1;
// Swap next pointers
struct node *temp = ptr_1->next;
ptr_1->next = ptr_2->next;
ptr_2->next = temp;
}
int main()
{
node *start=NULL;
/* The linked list is:
1->2->3->4->5->6->7 */
insert(&start,7);
insert(&start,6);
insert(&start,5);
insert(&start,4);
insert(&start,3);
insert(&start,2);
insert(&start,1);
/*Before Swap LinkList*/
printf("\nLinked List Before Swap of Nodes :");
printList(start);
swapNode(&start,3,5);
/*After Swap LinkList*/
printf("\nLinked List After Swap of Nodes :");
printList(start);
return 0;
}
// Structure of Node
struct node
{
int data;
struct node *next;
};
typedef struct node node;
//Function to insert data in linked list
void insert(node **ptr,int val)
{
node *nn=(node*)malloc(sizeof(node));
nn->data=val;
nn->next=*ptr;
/*Move start Pointer to head*/
*ptr=nn;
}
//Function to print linked list
void printList(node *ptr)
{
while(ptr!=NULL)
{
printf("%d ",ptr->data);
ptr=ptr->next;
}
}
//Function to swap nodes
void swapNode(node **head,int val_1,int val_2)
{
//If both values are same nothing to do
if(val_1==val_2)
return;
//Search for val_1
node *ptr_1=*head,*prev_1=NULL;
while(ptr_1 && ptr_1->data!=val_1)
{
prev_1=ptr_1;
ptr_1=ptr_1->next;
}
//Search for val_2
node *ptr_2=*head,*prev_2=NULL;
while(ptr_2 && ptr_2->data!=val_2)
{
prev_2=ptr_2;
ptr_2=ptr_2->next;
}
//Value not found
if(ptr_2==NULL || ptr_1==NULL)
return;
if(prev_1!=NULL)
prev_1->next=ptr_2;
else
*head==ptr_2;
if(prev_2!=NULL)
prev_2->next=ptr_1;
else
*head=ptr_1;
// Swap next pointers
struct node *temp = ptr_1->next;
ptr_1->next = ptr_2->next;
ptr_2->next = temp;
}
int main()
{
node *start=NULL;
/* The linked list is:
1->2->3->4->5->6->7 */
insert(&start,7);
insert(&start,6);
insert(&start,5);
insert(&start,4);
insert(&start,3);
insert(&start,2);
insert(&start,1);
/*Before Swap LinkList*/
printf("\nLinked List Before Swap of Nodes :");
printList(start);
swapNode(&start,3,5);
/*After Swap LinkList*/
printf("\nLinked List After Swap of Nodes :");
printList(start);
return 0;
}

No comments:
Post a Comment