Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on Linked List
  • Practice Linked List
  • MCQs on Linked List
  • Linked List Tutorial
  • Types of Linked List
  • Singly Linked List
  • Doubly Linked List
  • Circular Linked List
  • Circular Doubly Linked List
  • Linked List vs Array
  • Time & Space Complexity
  • Advantages & Disadvantages
Open In App
Next Article:
Reverse first K elements of given linked list
Next article icon

Pairwise Swap Elements of a given Linked List

Last Updated : 30 Sep, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report
Try it on GfG Practice
redirect icon

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

Reverse-a-Linked-List-in-groups-of-given-size-1


Input : 1 -> 2 -> 3 -> 4 -> 5 -> NULL 
Output : 2 -> 1 -> 4 -> 3 -> 5 -> NULL

Table of Content

  • [Expected Approach – 1] Using Recursion- O(n) Time and O(n) Space
  • [Expected Approach – 2] Using Iterative Method – O(n) Time and O(1) Space
  • [Expected Approach – 3] By Changing Links – O(n) Time and O(1) Space

[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); 

Output
2 1 4 3 6 5  

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); 

Output
2 1 4 3 6 5 

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

  • Pairwise Swap Nodes by Changing Links


Next Article
Reverse first K elements of given linked list
author
kartik
Improve
Article Tags :
  • DSA
  • Linked List
  • Amazon
  • Microsoft
  • Moonfrog Labs
Practice Tags :
  • Amazon
  • Microsoft
  • Moonfrog Labs
  • Linked List

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
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences