Pairwise swap elements of a given linked list

In this problem, we have given a linked list, and we need to pairwise swap elements of the given linked list.

Example:

                                    Input:1 ->3 ->5 ->7 ->9 ->0 ->4 ->8

                             Output:3 ->1 ->7 ->5 ->0 ->9 ->8 ->4

                             Input:2 ->6 ->5 ->1 ->9 ->0 ->3

                             Output:6 ->2 ->1 ->5 ->0 ->9 ->3

Method1:(Iterative)

In this method, we will traverse the linked list. While traversing, we will swapeach node data with its next node’s data by using the iterative approach.

C Program to pairwise swap elements of the linked list by iterative method

Output:

Pairwise swap elements of a given linked list

Time Complexity:The time complexity of this method is O(n).         

Method2: (Recursive)

In this method, we will do recursive callsto pairwise swap elements if there are two or morenodes in the linked list.

C Program to pairwise swap elements of the linked list by a recursive method

Output:

Pairwise swap elements of a given linked list

Time Complexity:The time complexity of this method is O(n).

Pin It on Pinterest

Share This