Swap alternate elements of Linked List pairwise


Today, we will discuss how to swap alternate elements of a linked list pairwise. But before starting make sure you have basic knowledge of linked lists. So, let's start, shall we?

Procedure


1. First we will make a linked list.
2. Now we will start traversing the linked list.
3. We will use a pointer to node which will consider 2 nodes at a time and then perform a swap operation on them.
4. Then we will increment pointer to node 2 times so that next pair can be swapped.
Don't worry if you can't understand the procedure thoroughly. Keep reading till end and you will be able to solve this problem on your own.

Algorithm


First we will write a simple code of linked list which will have 2 functions:
1. insert() - which will insert elements in the linked list.
2. disp() - which will display the linked list.
Insert some values in the linked list.
Then make a function swap() which will swap alternate elements of linked list pairwise.
In the swap() function first we will make a pointer to node named temp which will initially points to the head node.
Then we will make a variable 'p' which we will use in swapping.
Now we will iterate the linked list such that the current node and the pointer to next node is not NULL which means 2 nodes exists and we will swap them. Otherwise if there exists only 1 node in the end then we will leave it as it is.

Swap alternate elements of Linked List pairwise


Next we will perform a swap operation between current and next node.
p=temp->data;
temp->data=temp->next->data;
temp->next->data=p;
1. In the above swapping code we have stored the data of current node in a p.
2. Then in the data of current node we have placed the data of next node. 'temp->next->data' will point to the data portion of next node.
3. Then in the data of next node we have placed the value of p.

Swap alternate elements of Linked List pairwise


In this way we have swapped the values of 2 alternate nodes pairwise.
At last we will double increment temp so that it will point to next pair of nodes (temp=temp->next->next). 

Swap alternate elements of Linked List pairwise



Implementation in C++

OUTPUT:

Swap alternate elements of Linked List pairwise



Post a Comment (0)
Previous Post Next Post