Swapping of the node in Linked list:
Swapping of a node in the Linked list is one of the tough tasks.
We can swap values of node easily but not swapping node’s link is not easy so here is C++ code for swapping links of a node in the linked list.
Enjoy!
Advantages of Swapping Address In Linked List:
By swapping nodes of the linked list we can easily sort linked list in ascending or descending order. And complete our required task.
A big advantage of swapping node by changing links of node is that its values will not mix with each other our all data will remain secure.
Efficiency:
Swapping of a node with changing links is much faster than swapping all values of node one by one.
C++ Code:
#include<iostream> //header file
using namespace::std;
class item{ //item class starts
public:
int key;
float data;
item* next;
item(int k,float d)
{
key=k;
data=d;
next=NULL;
}
void display() //function to display data
{
cout<<"Key Is : "<<key<<" & Data Is : "<<data<<endl;
}
};
class linkedList{ //linked list class (main class)
private:
item* head;
public:
void insertAtEnd(item* i) //Function For Insertion
{
if(head==NULL)
{head=i;}else{
item* curr=head;
while(curr->next!=NULL)
{
curr=curr->next; //while curr is not equal to null
}
curr->next=i;
}
}
void displayList() //Function TO Display All Values
{
if(head==NULL)
{
cout<<"List Is Empty !"<<endl;
}
else{
item* curr=head;
while(curr!=NULL)
{
curr->display();
curr=curr->next;
}
}
}
void bSort(){ //function for swap nodes
item *preOfTemp = head;
item *nextOfTemp;
cout<<"\t\t\t********** After Sorting **********"<<endl;
while(preOfTemp!=NULL)
{
nextOfTemp = preOfTemp->next;
item *ptr3 = NULL;
while(nextOfTemp!=NULL)
{
ptr3 = nextOfTemp->next;
if(preOfTemp->key > nextOfTemp->key)
{
if(head->key > nextOfTemp->key)
head = nextOfTemp;
else
{
item* curr = head;
while(curr->next!= preOfTemp)
{
curr = curr->next;
}
curr->next = nextOfTemp;
}
// Now Swap Addresses
item* n = nextOfTemp->next;
if(preOfTemp->next==nextOfTemp)
{
nextOfTemp->next = preOfTemp;
}else
{
nextOfTemp->next = preOfTemp->next;
}
preOfTemp->next = n;
preOfTemp = nextOfTemp;
cout<<"Swap Successful"<<endl;
}
nextOfTemp = ptr3;
}
preOfTemp = preOfTemp->next;
}
}
}; //End Of Class
int main() //main function
{
linkedList* list=new linkedList();
list->insertAtEnd(new item(3,4.5));
list->insertAtEnd(new item(1,2.3));
list->insertAtEnd(new item(2,3.4));
list->insertAtEnd(new item(4,5.6));
cout<<"\t\t\t********** Before Sorting **********"<<endl;
list->displayList();
list->bSort();
list->displayList();
}
No comments:
Post a Comment