Pairwise Swap Elements of a given Linked List
Last Updated : 30 Sep, 2024
Given a singly linked list, the task is to swap linked list elements pairwise.
Examples:
Input : 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> NULL
Output : 2 -> 1 -> 4 -> 3 -> 6 -> 5 -> NULL

Input : 1 -> 2 -> 3 -> 4 -> 5 -> NULL
Output : 2 -> 1 -> 4 -> 3 -> 5 -> NULL
[Expected Approach – 1] Using Recursion- O(n) Time and O(n) Space
The idea is to swap the data of the first two adjacent nodes, then recursively move to the next pair of nodes. In each recursive call, the data of the current node is swapped with its next node, and the function continues to do so until there are fewer than two nodes left in the list.
Below is the implementation of the above approach:
C++ // C++ program to pairwise swap elements // in a given linked list #include <iostream> using namespace std; class Node { public: int data; Node* next; Node(int val) { data = val; next = nullptr; } }; // Recursive function to swap data of nodes in pairs void pairwiseSwap(Node* head) { // Base case: if the list is empty or has only // one node, no swap if (head == nullptr || head->next == nullptr) { return; } // Swap the data of the current node with the next node swap(head->data, head->next->data); // Recursion for the next pair pairwiseSwap(head->next->next); } void printList(Node* head) { Node* curr = head; while (curr != nullptr) { cout << curr->data << " "; curr = curr->next; } cout << endl; } int main() { // Creating the linked list: // 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> NULL Node* head = new Node(1); head->next = new Node(2); head->next->next = new Node(3); head->next->next->next = new Node(4); head->next->next->next->next = new Node(5); head->next->next->next->next->next = new Node(6); pairwiseSwap(head); printList(head); return 0; }
C // C program to pairwise swap elements // in a given linked list #include <stdio.h> #include <stdlib.h> struct Node { int data; struct Node* next; }; // Recursive function to swap data of nodes in pairs void pairwiseSwap(struct Node* head) { // Base case: if the list is empty or has // only one node, no swap if (head == NULL || head->next == NULL) { return; } // Swap the data of the current node with the next node int temp = head->data; head->data = head->next->data; head->next->data = temp; // Recursion for the next pair pairwiseSwap(head->next->next); } void printList(struct Node* head) { struct Node* curr = head; while (curr != NULL) { printf("%d ", curr->data); curr = curr->next; } printf("\n"); } struct Node* createNode(int val) { struct Node* newNode = (struct Node*)malloc(sizeof(struct Node)); newNode->data = val; newNode->next = NULL; return newNode; } int main() { // Creating the linked list: // 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> NULL struct Node* head = createNode(1); head->next = createNode(2); head->next->next = createNode(3); head->next->next->next = createNode(4); head->next->next->next->next = createNode(5); head->next->next->next->next->next = createNode(6); pairwiseSwap(head); printList(head); return 0; }
Java // Java program to pairwise swap elements // in a given linked list class Node { int data; Node next; Node(int val) { data = val; next = null; } } class GfG { // Recursive function to swap data of nodes in pairs static void pairwiseSwap(Node head) { // Base case: if the list is empty or has // only one node, no swap if (head == null || head.next == null) { return; } // Swap the data of the current node with the next node int temp = head.data; head.data = head.next.data; head.next.data = temp; // Recursion for the next pair pairwiseSwap(head.next.next); } static void printList(Node head) { Node curr = head; while (curr != null) { System.out.print(curr.data + " "); curr = curr.next; } System.out.println(); } public static void main(String[] args) { // Creating the linked list: // 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> NULL Node head = new Node(1); head.next = new Node(2); head.next.next = new Node(3); head.next.next.next = new Node(4); head.next.next.next.next = new Node(5); head.next.next.next.next.next = new Node(6); pairwiseSwap(head); printList(head); } }
Python # Python program to pairwise swap elements # in a given linked list class Node: def __init__(self, val): self.data = val self.next = None # Recursive function to swap data of nodes in pairs def pairwiseSwap(head): # Base case: if the list is empty or # has only one node, no swap if head is None or head.next is None: return # Swap the data of the current node with the next node head.data, head.next.data = head.next.data, head.data # Recursion for the next pair pairwiseSwap(head.next.next) def printList(head): curr = head while curr: print(curr.data, end=" ") curr = curr.next print() if __name__ == "__main__": # Creating the linked list: 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> None head = Node(1) head.next = Node(2) head.next.next = Node(3) head.next.next.next = Node(4) head.next.next.next.next = Node(5) head.next.next.next.next.next = Node(6) pairwiseSwap(head) printList(head)
C# // C# program to pairwise swap elements // in a given linked list using System; class Node { public int data; public Node next; public Node(int val) { data = val; next = null; } } class GfG { // Recursive function to swap data of nodes in pairs static void pairwiseSwap(Node head) { // Base case: if the list is empty or has // only one node, no swap if (head == null || head.next == null) { return; } // Swap the data of the current node with // the next node int temp = head.data; head.data = head.next.data; head.next.data = temp; // Recursion for the next pair pairwiseSwap(head.next.next); } static void printList(Node head) { Node curr = head; while (curr != null) { Console.Write(curr.data + " "); curr = curr.next; } Console.WriteLine(); } static void Main(string[] args) { // Creating the linked list: // 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> NULL Node head = new Node(1); head.next = new Node(2); head.next.next = new Node(3); head.next.next.next = new Node(4); head.next.next.next.next = new Node(5); head.next.next.next.next.next = new Node(6); pairwiseSwap(head); printList(head); } }
JavaScript // Javascript program to pairwise swap elements // in a given linked list class Node { constructor(val) { this.data = val; this.next = null; } } // Recursive function to swap data of nodes in pairs function pairwiseSwap(head) { // Base case: if the list is empty or // has only one node, no swap if (head === null || head.next === null) { return; } // Swap the data of the current node with the next node [head.data, head.next.data] = [head.next.data, head.data]; // Recursion for the next pair pairwiseSwap(head.next.next); } function printList(head) { let curr = head; while (curr !== null) { console.log(curr.data + " "); curr = curr.next; } console.log(); } // Creating the linked list: // 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> NULL let head = new Node(1); head.next = new Node(2); head.next.next = new Node(3); head.next.next.next = new Node(4); head.next.next.next.next = new Node(5); head.next.next.next.next.next = new Node(6); pairwiseSwap(head); printList(head);
Time complexity: O(n), where n is the number of nodes in the linked list.
Auxiliary Space: O(n), recursive stack space.
[Expected Approach – 2] Using Iterative Method – O(n) Time and O(1) Space
The idea is to traverse the linked list from head and swap the data between adjacent nodes in pairs. Starting from the head node, we swap the data of the current node with the next node, then move two steps forward to swap the next pair.
Below is the implementation of the above approach:
C++ // C++ program to pairwise swap elements // in a given linked list #include <iostream> using namespace std; class Node { public: int data; Node* next; Node(int val) { data = val; next = nullptr; } }; // Function to swap data of nodes in pairs void pairwiseSwap(Node* head) { Node* curr = head; // Traverse the list and swap data in pairs while (curr != nullptr && curr->next != nullptr) { // Swap data of current node and the next node swap(curr->data, curr->next->data); // Move to the next pair curr = curr->next->next; } } void printList(Node* head) { Node* curr = head; while (curr != nullptr) { cout << curr->data << " "; curr = curr->next; } } int main() { // Creating the linked list: // 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> NULL Node* head = new Node(1); head->next = new Node(2); head->next->next = new Node(3); head->next->next->next = new Node(4); head->next->next->next->next = new Node(5); head->next->next->next->next->next = new Node(6); pairwiseSwap(head); printList(head); return 0; }
C // C program to pairwise swap elements // in a given linked list #include <stdio.h> #include <stdlib.h> struct Node { int data; struct Node* next; }; // Function to swap data of nodes in pairs void pairwiseSwap(struct Node* head) { struct Node* curr = head; // Traverse the list and swap data in pairs while (curr != NULL && curr->next != NULL) { // Swap data of current node and the next node int temp = curr->data; curr->data = curr->next->data; curr->next->data = temp; // Move to the next pair curr = curr->next->next; } } void printList(struct Node* head) { struct Node* curr = head; while (curr != NULL) { printf("%d ", curr->data); curr = curr->next; } } struct Node* createNode(int val) { struct Node* newNode = (struct Node*)malloc(sizeof(struct Node)); newNode->data = val; newNode->next = NULL; return newNode; } int main() { // Creating the linked list: //1 -> 2 -> 3 -> 4 -> 5 -> 6 -> NULL struct Node* head = createNode(1); head->next = createNode(2); head->next->next = createNode(3); head->next->next->next = createNode(4); head->next->next->next->next = createNode(5); head->next->next->next->next->next = createNode(6); pairwiseSwap(head); printList(head); return 0; }
Java // Java program to pairwise // swap elements of a linked list class Node { int data; Node next; Node(int val) { data = val; next = null; } } class GfG { // Function to swap data of nodes in pairs static void pairwiseSwap(Node head) { Node curr = head; // Traverse the list and swap data in pairs while (curr != null && curr.next != null) { // Swap data of current node and the next node int temp = curr.data; curr.data = curr.next.data; curr.next.data = temp; // Move to the next pair curr = curr.next.next; } } static void printList(Node head) { Node curr = head; while (curr != null) { System.out.print(curr.data + " "); curr = curr.next; } } public static void main(String[] args) { // Creating the linked list: // 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> null Node head = new Node(1); head.next = new Node(2); head.next.next = new Node(3); head.next.next.next = new Node(4); head.next.next.next.next = new Node(5); head.next.next.next.next.next = new Node(6); pairwiseSwap(head); printList(head); } }
Python # Python program to swap the elements # of linked list pairwise class Node: def __init__(self, val): self.data = val self.next = None # Function to swap data of nodes in pairs def pairwiseSwap(head): curr = head # Traverse the list and swap data in pairs while curr is not None and curr.next is not None: # Swap data of current node and the next node curr.data, curr.next.data = curr.next.data, curr.data # Move to the next pair curr = curr.next.next def printList(head): curr = head while curr: print(curr.data, end=" ") curr = curr.next print() if __name__ == "__main__": # Creating the linked list: # 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> None head = Node(1) head.next = Node(2) head.next.next = Node(3) head.next.next.next = Node(4) head.next.next.next.next = Node(5) head.next.next.next.next.next = Node(6) pairwiseSwap(head) printList(head)
C# // C# program to pairwise swap elements // of a linked list using System; class Node { public int data; public Node next; public Node(int val) { data = val; next = null; } } class GfG { // Function to swap data of nodes in pairs public static void pairwiseSwap(Node head) { Node curr = head; // Traverse the list and swap data in pairs while (curr != null && curr.next != null) { // Swap data of current node and the next node int temp = curr.data; curr.data = curr.next.data; curr.next.data = temp; // Move to the next pair curr = curr.next.next; } } static void printList(Node head) { Node curr = head; while (curr != null) { Console.Write(curr.data + " "); curr = curr.next; } Console.WriteLine(); } static void Main() { // Creating the linked list: // 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> null Node head = new Node(1); head.next = new Node(2); head.next.next = new Node(3); head.next.next.next = new Node(4); head.next.next.next.next = new Node(5); head.next.next.next.next.next = new Node(6); pairwiseSwap(head); printList(head); } }
JavaScript // JavaScript program to pairwise swap // elements of a linked list class Node { constructor(val) { this.data = val; this.next = null; } } // Function to swap data of nodes in pairs function pairwiseSwap(head) { let curr = head; // Traverse the list and swap data in pairs while (curr !== null && curr.next !== null) { // Swap data of current node and the next node [curr.data, curr.next.data] = [curr.next.data, curr.data]; // Move to the next pair curr = curr.next.next; } } function printList(head) { let curr = head; while (curr !== null) { console.log(curr.data); curr = curr.next; } } // Creating the linked list: // 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> null let head = new Node(1); head.next = new Node(2); head.next.next = new Node(3); head.next.next.next = new Node(4); head.next.next.next.next = new Node(5); head.next.next.next.next.next = new Node(6); pairwiseSwap(head); printList(head);
Time complexity: O(n), where n is the number of nodes in the linked list.
Auxiliary Space: O(1)
[Expected Approach – 3] By Changing Links – O(n) Time and O(1) Space
The solution provided here swaps data of nodes. If the data contains many fields (for example a linked list of Student Objects), the swap operation will be costly. See the below article for a better solution that works well for all kind of linked lists
Similar Reads
XOR Linked List - Pairwise swap elements of a given linked list
Given a XOR linked list, the task is to pairwise swap the elements of the given XOR linked list . Examples: Input: 4 <-> 7 <-> 9 <-> 7Output: 7 <-> 4 <-> 7 <-> 9Explanation:First pair of nodes are swapped to formed the sequence {4, 7} and second pair of nodes are
12 min read
Reverse first K elements of given linked list
Given a pointer to the head node of a linked list and a number K, the task is to reverse the first K nodes of the linked list. We need to reverse the list by changing links between nodes. check also Reversal of a linked list Examples: Input : 1->2->3->4->5->6->7->8->9->10-
9 min read
Pairwise Swap Nodes of a given linked list by changing links
Given a singly linked list, write a function to swap elements pairwise. For example, if the linked list is 1->2->3->4->5->6->7 then the function should change it to 2->1->4->3->6->5->7, and if the linked list is 1->2->3->4->5->6 then the function sh
15+ min read
Move first element to end of a given Linked List
Write a C function that moves first element to end in a given Singly Linked List. For example, if the given Linked List is 1->2->3->4->5, then the function should change the list to 2->3->4->5->1. Algorithm: Traverse the list till last node. Use two pointers: one to store the
14 min read
Move last element to front of a given Linked List | Set 2
Given a singly linked list and an integer K. The task is to append last K elements of the linked list to front. Examples: Input: 1 -> 2 -> 3 -> 4 -> 5 -> 6, k = 3 Output : 4 -> 5 -> 6 -> 1 -> 2 -> 3 Input: 1 -> 2 -> 3 -> 4 -> 5 -> 6, k = 7 Output : 6 -
9 min read
Javascript Program For Pairwise Swapping Elements Of A Given Linked List By Changing Links
Given a singly linked list, write a function to swap elements pairwise. For example, if the linked list is 1->2->3->4->5->6->7 then the function should change it to 2->1->4->3->6->5->7, and if the linked list is 1->2->3->4->5->6 then the function sh
4 min read
Alternating split of a given Singly Linked List | Set 1
Write a function AlternatingSplit() that takes one list and divides up its nodes to make two smaller lists 'a' and 'b'. The sublists should be made from alternating elements in the original list. So if the original list is 0->1->0->1->0->1 then one sublist should be 0->0->0 and
15+ min read
Delete a Linked List node at a given position
Given a singly linked list and a position (1-based indexing), the task is to delete a linked list node at the given position. Note: Position will be valid (i.e, 1 <= position <= linked list length) Example: Input: position = 2, Linked List = 8->2->3->1->7Output: Linked List = 8-
8 min read
Move last element to front of a given Linked List
Given a singly linked list. The task is to move the last node to the front in a given List. Examples: Input: 2->5->6->2->1Output: 1->2->5->6->2Explanation : Node 1 moved to front. Input: 1->2->3->4->5Output: 5->1->2->3->4Explanation : Node 5 moved to f
8 min read
Pairwise swap adjacent nodes of a linked list by changing pointers | Set 2
Given a singly linked list, write a function to swap elements pairwise. Input : 1->2->3->4->5->6->7 Output : 2->1->4->3->6->5->7, Input : 1->2->3->4->5->6 Output : 2->1->4->3->6->5 A solution has been discussed set 1. Here a simpler s
13 min read