×

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

Difference between Stack and Queue

In this article, we will learn about the major differences between Stack and Queue data structures. What is a stack? Stack – A stack is an abstract data structure defined as the...

3 minutes read.

Stack vs Array

Difference between Array and Stack In this article, we are going to discuss the major differences between the stack and array data structures: Array – In the data structure, the array is...

3 minutes read.

2-3 Trees and Basic Operations on them

2-3 Trees, like any other AVL trees or B-trees, are just a type of Height Balanced Tree. 2-3 Trees are the B-trees of order 3. Like every other B-tree, the...

4 minutes read.

Lowest common ancestor in a binary search tree

Suppose you have given two values of nodes in a binary search tree. You have to find out the lowest common ancestor between the nodes. Let’s take an example tree- For the...

4 minutes read.

Box Stacking Problem

Stacking of boxes depending on their base You have been given n different boxes. These boxes will have different heights, widths, and depths. You have to stack all these boxes in...

4 minutes read.

Equal Sum

Find an element in array such that the sum of left array is equal to the sum of right array You have been given an array of numbers. You have to...

4 minutes read.

Counting Sort

Counting Sort: Counting sort is a sorting algorithm that is used to sort the elements of the array within a specific range. It counts the same element number of the...

3 minutes read.

Finding the Maximum Element in a Binary Tree

Implementation // Creating a C++ program to excavate the minimum and maximum in a given binary tree. #include <bits/stdc++.h> #include <iostream> using namespace std; // creating a new tree node. class __nod { public: int record; __nod *Lft, *Rt; /*...

4 minutes read.

Operations of B Tree in C++ Language

B tree tends to be a self-aligning and balancing tree that helps us organise our data and document safely. We know that every data or information in the B tree...

9 minutes read.

Traversal of binary tree

Traversal of binary tree: A node is visited only once in the traversal of the binary tree. There are three main types of traversal methods in the binary tree. In-order traversalPre-order...

3 minutes read.

Quick Sort

Quicksort is a sorting algorithm that uses a divide-and-conquer strategy. A pivot element is used to divide an array into subarrays (element selected from the array).  The pivot element should be...

4 minutes read.

Left View of Binary Tree

Implementation // creating a C++ program to print the Left view of the binary tree. #include <bits/stdc++.h> using namespace std; struct Nod { int record; struct Nod *Lft, *Rt; }; // creating a utility function that will eventually help...

4 minutes read.

Sum of Nodes in a Binary Tree

In this article, we will see the sample problems that will help us understand the concept and summation of all the nodes in the binary tree. Implementation /* creating a program that...

4 minutes read.

Post-order traversal in a binary tree

We all know that postorder is a form of tree traversal to visit the tree's nodes, and it helps us reach out to the tree's nodes. Postorder means visiting the...

4 minutes read.

Stack vs Heap Memory Allocation Data Structure

Difference Between Stack and Heap Memory Allocation Stack Memory Stack memory allocation is a way to use the system memory as a temporary storage of the data which is act like last-in-first-out...

3 minutes read.

Array Data Structure

Data Structure Array: The array is a non-primitive and linear data structure that is a group of similar data items. That is, it can store only one type of data....

6 minutes read.

Strictly binary tree in Data Structures?

What is a strictly Binary Tree in Data Structures? There are various kinds of binary trees that we know exist in data structures, and they all have their purposes. In this...

4 minutes read.

Depth of binary tree

We all know that a binary tree is a kind of tree that helps us maintain the order and balance of the tree. It is a type of tree in...

4 minutes read.

Tree in Data Structure

Tree A tree is a non-linear data structure by which hierarchical data is displayed. As we know that there are many trees in the forest, similarly the data structure also contains...

3 minutes read.

Operations on 2D-Arrays

Two Dimensional Array Operations Adding Elements to Two-D Arrays We must put data in both rows and columns when inserting items in 2-D Arrays. As a result, we employ the idea of...

10 minutes read.