Pairwise Swap in a Linked List

Last Updated : 10 Apr, 2026

Given a singly linked list, swap every two adjacent nodes.

Examples:

Input :

1

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

Input :

3


Output : 7 -> 8 -> 2 -> 5 -> 1

Try It Yourself
redirect icon

Swapping Data - O(n) Time and O(1) Space

  • Start from head and initialize curr = head. Traverse while curr != NULL and curr->next != NULL.
  • Swap data of current pair (curr->data <-> curr->next->data).
  • Move to the next pair using curr = curr->next->next.
  • Stop when no pair remains
C++
#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* temp = head;
    while (temp != nullptr) {
        cout << temp->data ;
        if(temp->next!=nullptr)
        cout<<" -> ";
        temp = temp->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
#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);
        if(curr->next)
        printf(" -> ");
        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
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 temp = head;
        while (temp != null) {
            System.out.print(temp.data);
            if(temp.next!=null)
            {
                System.out.print(" -> ");
            }
            temp = temp.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
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(node):
    while node is not None:
        print(f"{node.data}", end="")
        if node.next is not None:
            print(" -> ", end="")
        node = node.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#
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 temp = head;
        while (temp != null) {
            Console.Write(temp.data + "");
            if(temp.next!=null)
            Console.Write(" -> ");
            temp = temp.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
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(node) {
    while (node !== null) {
        process.stdout.write(node.data.toString());
        if (node.next !== null) {
            process.stdout.write(" -> ");
        }
        node = node.next;
    }
}
// Driver Code
// 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

Instead of swapping the data inside nodes, we change the links (pointers) between nodes. This avoids heavy data movement, especially when nodes store complex objects (like student records).

We keep track of the previous node while traversing and change next of current to previous. We need ensure that proper pointers are set before the next iteration of the loop.

C++
#include <iostream>
using namespace std;

// A linked list node 
struct Node {
    int data;
    Node* next;

    Node(int x) {
        data = x;
        next = NULL;
    }
};

// Function to pairwise swap nodes 
Node* pairwiseSwap(Node* head)
{
    // Handle base cases 
    if (head == NULL || head->next == NULL)
        return head;

    // Initialize pointers for 
    // first node of pair and second node of pair
    Node* prev = head;         
    Node* curr = head->next;  

    // Update head to second node (after first swap)
    head = curr;

    // Traverse list in pairs
    while (true) {

        // Store next pair starting node
        Node* next = curr->next;

        // Perform swap of current pair
        curr->next = prev;

        // If no more pairs OR only one node left
        if (next == NULL || next->next == NULL) {
            
            // connect remaining node (if exists)
            prev->next = next;
            break;
        }
        
        // Connect current swapped pair to next swapped pair
        prev->next = next->next;

        // Move pointers to next pair
        prev = next;
        curr = prev->next;
    }
    
    // Step 10: Return new head
    return head;
}

// Print in required format 
void printList(Node* node)
{
    while (node != NULL) {
        cout << node->data;
        if (node->next != NULL)
            cout << " -> ";

        node = node->next;
    }
}

// Driver code 
int main()
{
    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 = pairwiseSwap(head);
    printList(head);
    return 0;
}
Java
import java.io.*;

// A linked list node 
class Node {
    int data;
    Node next;

    Node(int x) {
        data = x;
        next = null;
    }
}

public class Main {
    
    // Function to pairwise swap nodes 
    static Node pairwiseSwap(Node head)
    {
        // Handle base cases 
        if (head == null || head.next == null)
            return head;

        // Initialize pointers for 
        // first node of pair and second node of pair
        Node prev = head;          
        Node curr = head.next;  

        // Update head to second node (after first swap)
        head = curr;

        // Traverse list in pairs
        while (true) {

            // Store next pair starting node
            Node next = curr.next;

            // Perform swap of current pair
            curr.next = prev;

            // If no more pairs OR only one node left
            if (next == null || next.next == null) {
                
                // connect remaining node (if exists)
                prev.next = next;
                break;
            }
            
            // Connect current swapped pair to next swapped pair
            prev.next = next.next;

            // Move pointers to next pair
            prev = next;
            curr = prev.next;
        }
        
        // Step 10: Return new head
        return head;
    }

    // Print in required format 
    static void printList(Node node)
    {
        while (node!= null) {
            System.out.print(node.data);
            if (node.next!= null)
                System.out.print(" -> ");

            node = node.next;
        }
    }

    // Driver code 
    public static void main(String[] args)
    {
        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 = pairwiseSwap(head);
        printList(head);
    }
}
Python
# A linked list node 
class Node:
    def __init__(self, x):
        self.data = x
        self.next = None

# Function to pairwise swap nodes 
def pairwiseSwap(head):
    
    # Handle base cases 
    if head is None or head.next is None:
        return head

    # Initialize pointers for 
    # first node of pair and second node of pair
    prev = head      
    curr = head.next

    # Update head to second node (after first swap)
    head = curr

    # Traverse list in pairs
    while True:

        # Store next pair starting node
        next_node = curr.next

        # Perform swap of current pair
        curr.next = prev

        # If no more pairs OR only one node left
        if next_node is None or next_node.next is None:
            
            # connect remaining node (if exists)
            prev.next = next_node
            break
        
        # Connect current swapped pair to next swapped pair
        prev.next = next_node.next

        # Move pointers to next pair
        prev = next_node
        curr = prev.next
    
    # Step 10: Return new head
    return head

# Print in required format 
def printList(node):
    while node is not None:
        print(node.data, end="")
        if node.next is not None:
            print(" -> ", end="")

        node = node.next

# Driver code 
if __name__ == "__main__":
    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 = pairwiseSwap(head)
    printList(head)
C#
using System;

// A linked list node 
public class Node {
    public int data;
    public Node next;

    public Node(int x) {
        data = x;
        next = null;
    }
}

public class Program {
    
    // Function to pairwise swap nodes 
    public static Node pairwiseSwap(Node head) {
        
        // Handle base cases 
        if (head == null || head.next == null)
            return head;

        // Initialize pointers for 
        // first node of pair and second node of pair
        Node prev = head;          
        Node curr = head.next;  

        // Update head to second node (after first swap)
        head = curr;

        // Traverse list in pairs
        while (true) {

            // Store next pair starting node
            Node next = curr.next;

            // Perform swap of current pair
            curr.next = prev;

            // If no more pairs OR only one node left
            if (next == null || next.next == null) {
                
                // connect remaining node (if exists)
                prev.next = next;
                break;
            }
            
            // Connect current swapped pair to next swapped pair
            prev.next = next.next;

            // Move pointers to next pair
            prev = next;
            curr = prev.next;
        }
        
        // Step 10: Return new head
        return head;
    }

    // Print in required format 
    public static void printList(Node node) {
        while (node!= null) {
            Console.Write(node.data);
            if (node.next!= null)
                Console.Write(" -> ");

            node = node.next;
        }
    }

    // Driver code 
    public static void Main() {
        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 = pairwiseSwap(head);
        printList(head);
    }
}
JavaScript
// A linked list node 
function Node(x) {
    this.data = x;
    this.next = null;
}

// Function to pairwise swap nodes 
function pairwiseSwap(head) {
    
    // Handle base cases 
    if (head === null || head.next === null)
        return head;

    // Initialize pointers for 
    // first node of pair and second node of pair
    let prev = head;          
    let curr = head.next;  

    // Update head to second node (after first swap)
    head = curr;

    // Traverse list in pairs
    while (true) {

        // Store next pair starting node
        let next = curr.next;

        // Perform swap of current pair
        curr.next = prev;

        // If no more pairs OR only one node left
        if (next === null || next.next === null) {
            
            // connect remaining node (if exists)
            prev.next = next;
            break;
        }
        
        // Connect current swapped pair to next swapped pair
        prev.next = next.next;

        // Move pointers to next pair
        prev = next;
        curr = prev.next;
    }
    
    // Step 10: Return new head
    return head;
}

// Print in required format 
function printList(node) {
    while (node!== null) {
        process.stdout.write(node.data.toString());
        if (node.next!== null)
            process.stdout.write(" -> ");

        node = node.next;
    }
}

// Driver code 
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 = pairwiseSwap(head);
printList(head);

Output
2 -> 1 -> 4 -> 3 -> 6 -> 5
Comment