×

Pairwise swap elements of a given linked list

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

 #include<stdio.h>
 #include<stdlib.h>
 // The structure of the node
 struct node
 {
 int info;
 struct node * next;
 };
 struct node * start = NULL;
 // For inserting the elements in the linked list
 void add(int item)
 {
 struct node * t, * p;
 t = (struct node * )malloc( sizeof( struct node ));
 if(start == NULL)
 {
 start = t;
 start-> info = item;
 start-> next = NULL;
 return;
 }
 else
 {
 struct node * p = start;
 while(p -> next != NULL)
 {
 p = p ->next;
 }
 p-> next = t;
 p = p ->next;
 p->info = item;
 p ->next = NULL;
 }
 }
 // For swapping two elements
 void swap(int* a, int* b)
 {
 int temp;
 temp = *a;
     *a = *b;
     *b = temp;
 }
 // For the pairwise swap, the elements of the linked list
 voidpairWiseSwap(struct node* temp)
 {
 while(temp != NULL && temp ->next != NULL) {
 swap(&temp ->info, &temp ->next ->info);
 temp = temp ->next ->next;
     }
 }
 // To display the elements of the linked list
 void traverse(struct node * t)
 {
 if(t == NULL)
 {
             printf(" Linked list is empty\n");
                                     }
                                     while(t ->next != NULL)
                                     {
                         printf("%d  ->  ", t ->info);
                         t = t ->next;
                         }
                         printf("%d\n", t ->info);
 }
 // Driver Function
 int main()
 {
 add(1);
 add(3);
 add(5);
 add(7);
 add(9);
 add(0);
 add(4);
 add(8);
 printf("Linked List before pairwise swap:\n");
 traverse(start);
 pairWiseSwap(start);
 printf("Linked List after pairwise swap:\n");
 traverse(start);
 return 0;
 } 

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

 #include<stdio.h>
 #include<stdlib.h>
 // The structure of the node
 struct node
 {
 int info;
 struct node * next;
 };
 struct node * start = NULL;
 // For inserting the elements in the linked list
 void add(int item)
 {
 struct node * t, * p;
 t = (struct node * )malloc( sizeof( struct node ));
 if(start == NULL)
 {
 start = t;
 start ->info = item;
 start-> next = NULL;
 return;
 }
 else
 {
 struct node * p = start;
 while(p -> next != NULL)
 {
 p = p ->next;
 }
 p->next = t;
 p = p ->next;
 p->info = item;
 p ->next = NULL;
 }
 }
 // For swapping two elements
 void swap(int* a, int* b)
 {
 int temp;
 temp = *a;
     *a = *b;
     *b = temp;
 }
 // For the pairwise swap, the elements of the linked list
 voidpairWiseSwap(struct node* head)
 {
 if (head != NULL && head ->next != NULL) {
 swap(&head ->data, &head ->next ->data);
 pairWiseSwap(head ->next ->next);
     }
 }
 // To display the elements of the linked list
 void traverse(struct node * t)
 {
 if(t == NULL)
 {
             printf(" Linked list is empty\n");
                                     }
                                     while(t ->next != NULL)
                                     {
                         printf("%d -> ", t -> info);
                         t = t -> next;
                         }
                         printf("%d\n", t ->info);
 }
 // Driver Function
 int main()
 {
 add(1);
 add(3);
 add(5);
 add(7);
 add(9);
 add(0);
 add(4);
 add(8);
 printf("Linked List before pairwise swap:\n");
 traverse(start);
 pairWiseSwap(start);
 printf("Linked List after pairwise swap:\n");
 traverse(start);
 return 0;
 } 

Output:

Pairwise swap elements of a given linked list

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


Related Topics

Check if a Singly Linked List is Palindrome

Check if a Singly Linked List is Palindrome In this section, we have given a singly linked list, and we need to check whether the given list is a palindrome. Example:           1...

3 minutes read.

Given a Binary Tree Print the Shortest Path

Implementation // Writing a program in C++ to find the shortest between the nodes i and j.  #include <bits/stdc++.h> using namespace std; // the given function will print the path between nodes i and...

7 minutes read.

Given Two Binary Trees, Check if it is Symmetric

Implementation // creating a C++ program that will help us check whether the two given trees are mirror images of each other.  #include<bits/stdc++.h> using namespace std; /* A given binary tree has a data...

5 minutes read.

Given a Perfect Binary Tree, Reverse Alternate Levels

Implementation //writing a program in C++ language to see how to approach it. #include <bits/stdc++.h> using namespace std; // creating a tree node. struct Nod { char ky; struct Nod *Lft, *Rt; }; // creating a new utility function...

9 minutes read.

Stack Data Structure

The stack is a non-primitive and linear data structure. It works on the principle of LIFO (Last In First Out). That is, the element that is added to the end...

3 minutes read.

Winner tree in Data Structures

Tree Data structure A tree is a hierarchical and non-linear data structure with nodes. Each node in the Tree contains a message value and stores the name passed to another ("child")...

6 minutes read.

Linear vs Binary Search: Data Structure

Difference Between Linear and Binary Search What is Linear Search? A linear search also referred as a sequential search. It is a way to find an element within a list and it...

3 minutes read.

Reverse the Singly Linked List in C

Reverse the Singly Linked List in C This article has given a singly linked list and will reverse the linked list by changing the links between nodes. Example:                         Input:  2 -> 4...

3 minutes read.

What is a Tree in Terms of a Graph?

To know the explanation of trees in terms of graphs, we need first to know what trees and graphs are. So let us first learn about trees and graphs. Trees and...

6 minutes read.

Linear Queue Data Structure in C

Data Structure There are many ways to store data in programming, that Queue has features that make it all the more special. We all know that data structure is a way...

9 minutes read.

Insertion Sort vs Selection Sort

In this article, we will discuss insertion sort, Selection sort and the basic differences between these two sorting techniques in detail: What is Insertion Sort? Insertion Sort – The insertion sort is...

5 minutes read.

Binary Search Tree

Binary Search Tree: A binary search tree is a type of tree in which every node is organized in the sorted order. It is also called an ordered binary tree. Properties...

4 minutes read.

Berkley’s Algorithm

Berkley’s Algorithm is mainly used in clock synchronization system. It is used in distributed systems. To implement this algorithm, we have to think that the network has no accurate time...

4 minutes read.

Sorting Algorithms

Sorting: In the data structure, sorting is the process by which you arrange the data in a logical order. This logical order can also be an ascending order or a...

7 minutes read.

Heap Data Structure

In this article, we will learn in detail about Heap (Min heap and Max heap). Before going to the main topics, let’s have a look at what is complete binary...

19 minutes read.

Linear vs Circular Queue: Data Structure

Difference Between Linear and Circular Queue What is Linear Queue? A linear queue is linear data structure which works on first in first out principle. We can say a linear queue is...

3 minutes read.

Fundamental of Algorithms

An algorithm is a part of any programming solution or coding. If we have to make a solution then first we have to think of a clear idea about the...

13 minutes read.

Binary tree insertion

As we all know, a binary tree has a maximum of two children and helps us manage the info correctly. Here the name of the tree itself portrays the mechanism...

4 minutes read.

Merge Conflicts and ways to handle them

Merge Conflicts Whenever dealing with the Git merge operations, conflicts will be the frequently occurred. When more than two developers work on the same file on different systems using Git, they...

4 minutes read.

AVL Tree

AVL Tree AVL Tree is referred to as self-balanced or height-balanced binary search tree where the difference between heights of its left subtree and right subtree (Balance Factor) can't more than...

25 minutes read.