Pairwise Swap in a Linked List

Last Updated : 11 Jul, 2026

Given the head of a singly linked list, swap every two adjacent nodes and return the new head.

Note: Try to swap the nodes, not only the data.

Examples:

Input :

1

Output : 2 -> 1 -> 4 -> 3 -> 5
Explanation: The list has 5 nodes, so we form pairs from the front: [1, 2], [3, 4], and 5 remains unpaired (odd node count). Swapping each pair gives: [2, 1], [4, 3], and 5 stays as is. Final list: 2 -> 1 -> 4 -> 3 -> 5.

Input :

3

Output : 7 -> 8 -> 2 -> 5 -> 1
Explanation: The list has 5 nodes, so we form pairs from the front: [8, 7], [5, 2], and 1 remains unpaired (odd node count). Swapping each pair gives: [7, 8], [2, 5], and 1 stays as is. Final list: 7 -> 8 -> 2 -> 5 -> 1.

Try It Yourself
redirect icon

[Naive Approach] - Swapping Data - O(n) Time and O(1) Space

Instead of changing the structure of the linked list, swap the data stored in every adjacent pair of nodes. Since only the values are exchanged, the links between nodes remain unchanged. This approach is simple and works well when swapping node data is inexpensive.

  • Start from the head and initialize curr = head.
  • Traverse the list while curr and curr->next are not NULL.
  • Swap the data of the current pair (curr->data and curr->next->data).
  • Move curr two nodes ahead to process the next pair.
  • Stop when fewer than two nodes remain.
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
Node *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;
    }
    return head;
}
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
struct Node *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;
    }
    return head;
}

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
import java.util.*;

class Node {
    public int data;
    public Node next;

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

public class Main {
    // Function to swap data of nodes in pairs
    public static Node 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;
        }
        return head;
    }

    public 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
    return head


def printList(head):
    temp = head
    while temp is not None:
        print(temp.data, end="")
        if temp.next is not None:
            print(" -> ", end="")
        temp = temp.next
    print()


if __name__ == '__main__':
    # Creating the linked list:
    # 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> NULL
    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;

public class Node {
    public int data;
    public Node next;

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

public class Program {
    // Function to swap data of nodes in pairs
    public static Node 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;
        }
        return head;
    }

    public 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();
    }

    public 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;
    }
    return head;
}

function printList(head)
{
    let temp = head;
    while (temp !== null) {
        process.stdout.write(temp.data.toString());
        if (temp.next !== null)
            process.stdout.write(" -> ");
        temp = temp.next;
    }
    console.log();
}

// Main execution
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, swap the nodes themselves by updating their next pointers. This is more efficient when nodes store large or complex data, as only the links are modified while the node contents remain unchanged.

  • Handle the cases where the list has fewer than two nodes.
  • Initialize prev and curr to the first and second nodes of the current pair, and update head to curr.
  • For each pair, store the starting node of the next pair before modifying any links.
  • Reverse the link between the current pair by making curr->next point to prev.
  • If no more pairs remain (or only one node is left), connect the remaining node and stop.
  • Otherwise, connect the current swapped pair to the next swapped pair.
  • Move prev and curr to the next pair and repeat until all pairs are processed.
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 -> 5
Comment