#include <iostream>
using namespace std;
struct list
{
int data;
struct list *next;
};
typedef struct list node;
int Print(node *head)
{
node *temp=head;
if(head==NULL)
{
cout<<"
This Linked List is Empty
";
return 0;
}
else
{
cout<<"Liked List: "<<endl;
while(temp !=NULL)
{
cout<<temp->data<<" ";
temp=temp->next;
}
}
}
void swap_node(node *head,int n,int m)
{
node *n_node,*m_node,*temp;
int i;
temp=head;
while(temp->data!=NULL)
{
if(temp->data==n)
{
n_node=temp;
break;
}
temp=temp->next;
}
temp=head;
while(temp->data!=NULL)
{
if(temp->data==m)
{
m_node=temp;
break;
}
temp=temp->next;
}
int temp1;
///swap n and m position
temp1 = n_node->data;
n_node->data=m_node->data;
m_node->data=temp1;
}
int main()
{
int n,m,flag;
node *head=NULL;
node *last,*temp,*start=head;
do
{
cout<<"Press 1 to Insert Data: ";
cin>>flag;
if(flag!=1)break;
temp=new node();
cout<<"Data: ";
cin>>temp->data;
temp->next=NULL;
if(start==NULL)
{
start=temp;
head=temp;
}
else
{
last = start;
while(last->next!=NULL)
{
last = last->next;
}
last->next=temp;
}
}
while(flag==1);
Print(head);
cout<<"
Enter Two Value for Swap: ";
cin>>n;
cin>>m;
swap_node(head,n,m);
cout<<"
After Swap: ";
Print(head);
return 0;
}
Output
Press 1 to Insert Data: 1
Data: 3
Press 1 to Insert Data: 1
Data: 7
Press 1 to Insert Data: 1
Data: 6
Press 1 to Insert Data: 1
Data: 9
Press 1 to Insert Data: 0
Liked List:
3 7 6 9
Enter Two Value for Swap: 7 9
After Swap: Liked List:
3 9 6 7
Add your comment