Today we will discuss how to swap a node with its previous node in a linked list. But, if you are new to linked lists then please refer to this link where I have explained everything about linked lists. So, let's start shall we?
Procedure
1. First we w 1. First we will make a linked list.
2. Then user will enter the position 'p' of the node which is to be swapped with its previous node. ill make a linked list.
2. Then user will enter the position 'p' of the node which is to be swapped with its previous node.
2. Then user will enter the position 'p' of the node which is to be swapped with its previous node. ill make a linked list.
2. Then user will enter the position 'p' of the node which is to be swapped with its previous node.
3. Then we will iterate the list till that position 'p-1' and then we will swap the data of the previous node and the node at position 'p'.
Code
Explanation of code(line by line)
1. First we will write a simple code of linked list which will have 2 functions:
- insert() - which will insert elements in the linked list.
- disp() - which will display the linked list.
- disp() - which will display the linked list.
2. Insert some values in the linked list.
3. Now we have created a function named swap() to swap a node with previous node in a linked list. It will take an argument 'x' which denotes the position of the node which is to be swapped with its previous node.
3. Now we have created a function named swap() to swap a node with previous node in a linked list. It will take an argument 'x' which denotes the position of the node which is to be swapped with its previous node.
4. Then we have created variables:
- temp - Which is a pointer to node. It is initialized to head.
- c - It is a variable which will be used in iterating the list. It is initialized to 1.
- t - It is another variable which will be helping us in swapping data.
if(x<=1)
cout<<"exception";
cout<<"exception";
6. Otherwise we will enter the else condition.
7. Then we have iterated the list till the node which contain the address of the previous node.
while(c<x-1)
{
temp=temp->next;
c++;
}
{
temp=temp->next;
c++;
}
8. Then we have placed the data of the previous node in variable 't'.
t=temp->data;
9. Then we have placed the data of the node ahead of previous node in previous node.
temp->data=temp->next->data;
10. Then we have placed the data in 't' in the node ahead of previous node.
temp->next->data=t;
11. Then we have called the disp() which will display the list after swapping.