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:
Pairwise swap adjacent nodes of a linked list by changing pointers | Set 2
Next article icon

Pairwise Swap Nodes of a given linked list by changing links

Last Updated : 06 Feb, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

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 should change it to 2->1->4->3->6->5

This problem has been discussed here. The solution provided there swaps data of nodes. If data contains many fields, there will be many swap operations. So changing links is a better idea in general. Following is the implementation that changes links instead of swapping data. 

Implementation:

C++




/* This program swaps the nodes of
linked list rather than swapping the
field from the nodes.
Imagine a case where a node contains
many fields, there will be plenty
of unnecessary swap calls. */
 
#include <bits/stdc++.h>
using namespace std;
 
/* A linked list node */
class node {
public:
    int data;
    node* next;
};
 
/* Function to pairwise swap elements
of a linked list. It returns head of
the modified list, so return value
of this node must be assigned */
node* pairWiseSwap(node* head)
{
    // If linked list is empty or
    // there is only one node in list
    if (head == NULL || head->next == NULL)
        return head;
  
    // Initialize previous and current pointers
    node* prev = head;
    node* curr = head->next;
  
    head = curr; // Change head before proceeding
  
    // Traverse the list
    while (true) {
        node* next = curr->next;
        curr->next = prev; // Change next of
        // current as previous node
  
        // If next NULL or next is the last node
        if (next == NULL || next->next == NULL) {
            prev->next = next;
            break;
        }
  
        // Change next of previous to next of next
        prev->next = next->next;
  
        // Update previous and curr
        prev = next;
        curr = prev->next;
    }
    return head;
}
 
/* Function to add a node at
the beginning of Linked List */
void push(node** head_ref, int new_data)
{
    /* allocate node */
    node* new_node = new node();
 
    /* put in the data */
    new_node->data = new_data;
 
    /* link the old list of the new node */
    new_node->next = (*head_ref);
 
    /* move the head to point to the new node */
    (*head_ref) = new_node;
}
 
/* Function to print nodes
in a given linked list */
void printList(node* node)
{
    while (node != NULL) {
        cout << node->data << " ";
        node = node->next;
    }
}
 
/* Driver code */
int main()
{
    node* start = NULL;
 
    /* The constructed linked list is:
    1->2->3->4->5->6->7 */
    push(&start, 7);
    push(&start, 6);
    push(&start, 5);
    push(&start, 4);
    push(&start, 3);
    push(&start, 2);
    push(&start, 1);
 
    cout << "Linked list before "
      << "calling pairWiseSwap() ";
    printList(start);
 
    start = pairWiseSwap(start); // NOTE THIS CHANGE
 
    cout << "\nLinked list after calling"
      << "pairWiseSwap() ";
    printList(start);
 
    return 0;
}
 
// This code is contributed by Manoj N
 
 

C




/* This program swaps the nodes of linked list rather than swapping the
field from the nodes.
Imagine a case where a node contains many fields, there will be plenty
of unnecessary swap calls. */
 
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
 
/* A linked list node */
struct Node {
    int data;
    struct Node* next;
};
 
/* Function to pairwise swap elements of a linked list */
void pairWiseSwap(struct Node** head)
{
    // If linked list is empty or there is only one node in list
    if (*head == NULL || (*head)->next == NULL)
        return;
 
    // Initialize previous and current pointers
    struct Node* prev = *head;
    struct Node* curr = (*head)->next;
 
    *head = curr; // Change head before proceeding
 
    // Traverse the list
    while (true) {
        struct Node* next = curr->next;
        curr->next = prev; // Change next of current as previous node
 
        // If next NULL or next is the last node
        if (next == NULL || next->next == NULL) {
            prev->next = next;
            break;
        }
 
        // Change next of previous to next next
        prev->next = next->next;
 
        // Update previous and curr
        prev = next;
        curr = prev->next;
    }
}
 
/* Function to add a node at the beginning of Linked List */
void push(struct Node** head_ref, int new_data)
{
    /* allocate node */
    struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));
 
    /* put in the data  */
    new_node->data = new_data;
 
    /* link the old list of the new node */
    new_node->next = (*head_ref);
 
    /* move the head to point to the new node */
    (*head_ref) = new_node;
}
 
/* Function to print nodes in a given linked list */
void printList(struct Node* node)
{
    while (node != NULL) {
        printf("%d ", node->data);
        node = node->next;
    }
}
 
/* Driver program to test above function */
int main()
{
    struct Node* start = NULL;
 
    /* The constructed linked list is:
     1->2->3->4->5->6->7 */
    push(&start, 7);
    push(&start, 6);
    push(&start, 5);
    push(&start, 4);
    push(&start, 3);
    push(&start, 2);
    push(&start, 1);
 
    printf("\n Linked list before calling  pairWiseSwap() ");
    printList(start);
 
    pairWiseSwap(&start);
 
    printf("\n Linked list after calling  pairWiseSwap() ");
    printList(start);
 
    getchar();
    return 0;
}
 
 

Java




// Java program to swap elements of linked list by changing links
 
class LinkedList {
 
    static Node head;
 
    static class Node {
 
        int data;
        Node next;
 
        Node(int d)
        {
            data = d;
            next = null;
        }
    }
 
    /* Function to pairwise swap elements of a linked list */
    Node pairWiseSwap(Node node)
    {
 
        // If linked list is empty or there is only one node in list
        if (node == null || node.next == null) {
            return node;
        }
 
        // Initialize previous and current pointers
        Node prev = node;
        Node curr = node.next;
 
        node = curr; // Change head before proceeding
 
        // Traverse the list
        while (true) {
            Node next = curr.next;
            curr.next = prev; // Change next of current as previous node
 
            // If next NULL or next is the last node
            if (next == null || next.next == null) {
                prev.next = next;
                break;
            }
 
            // Change next of previous to next next
            prev.next = next.next;
 
            // Update previous and curr
            prev = next;
            curr = prev.next;
        }
        return node;
    }
 
    /* Function to print nodes in a given linked list */
    void printList(Node node)
    {
        while (node != null) {
            System.out.print(node.data + " ");
            node = node.next;
        }
    }
 
    // Driver program to test above functions
    public static void main(String[] args)
    {
 
        /* The constructed linked list is:
         1->2->3->4->5->6->7 */
        LinkedList list = new LinkedList();
        list.head = new Node(1);
        list.head.next = new Node(2);
        list.head.next.next = new Node(3);
        list.head.next.next.next = new Node(4);
        list.head.next.next.next.next = new Node(5);
        list.head.next.next.next.next.next = new Node(6);
        list.head.next.next.next.next.next.next = new Node(7);
 
        System.out.println("Linked list before calling pairwiseSwap() ");
        list.printList(head);
        Node st = list.pairWiseSwap(head);
        System.out.println("");
        System.out.println("Linked list after calling pairwiseSwap() ");
        list.printList(st);
        System.out.println("");
    }
}
 
// This code has been contributed by Mayank Jaiswal
 
 

Python3




# Python3 program to swap elements of
# linked list by changing links
 
# Linked List Node
class Node:
     
    def __init__(self, data):
         
        self.data = data
        self.next = None
 
# Create and Handle list operations
class LinkedList:
     
    def __init__(self):
         
        # Head of list
        self.head = None
 
    # Add data to list
    def addToList(self, data):
         
        newNode = Node(data)
        if self.head is None:
            self.head = newNode
            return
 
        last = self.head
         
        while last.next:
            last = last.next
 
        last.next = newNode
 
    # Function to print nodes
    # in a given linked list
    def __str__(self):
         
        linkedListStr = ""
        temp = self.head
         
        while temp:
            linkedListStr = (linkedListStr +
                            str(temp.data) + " ")
            temp = temp.next
             
        return linkedListStr
 
    # Function to pairwise swap elements
    # of a linked list. It returns head of
    # the modified list, so return value
    # of this node must be assigned
    def pairWiseSwap(self):
 
        # If list is empty or with one node
        if (self.head is None or
            self.head.next is None):
            return
 
        # Initialize previous and current pointers
        prevNode = self.head
        currNode = self.head.next
 
        # Change head node
        self.head = currNode
 
        # Traverse the list
        while True:
            nextNode = currNode.next
             
            # Change next of current
            # node to previous node
            currNode.next = prevNode 
 
            # If next node is the last node
            if nextNode.next is None:
                prevNode.next = nextNode
                break
 
            # Change next of previous to
            # next of next
            prevNode.next = nextNode.next
 
            # Update previous and current nodes
            prevNode = nextNode
            currNode = prevNode.next
 
# Driver Code
linkedList = LinkedList()
linkedList.addToList(1)
linkedList.addToList(2)
linkedList.addToList(3)
linkedList.addToList(4)
linkedList.addToList(5)
linkedList.addToList(6)
linkedList.addToList(7)
 
print("Linked list before calling" 
      "pairwiseSwap() ",
      linkedList)
       
linkedList.pairWiseSwap()
 
print("Linked list after calling "
      "pairwiseSwap() ",
      linkedList)
 
# This code is contributed by AmiyaRanjanRout
 
 

C#




// C# program to swap elements of
// linked list by changing links
using System;
 
public class LinkedList {
 
    Node head;
 
    public class Node {
 
        public int data;
        public Node next;
 
        public Node(int d)
        {
            data = d;
            next = null;
        }
    }
 
    /* Function to pairwise swap
    elements of a linked list */
    Node pairWiseSwap(Node node)
    {
 
        // If linked list is empty or there
        // is only one node in list
        if (node == null || node.next == null) {
            return node;
        }
 
        // Initialize previous and current pointers
        Node prev = node;
        Node curr = node.next;
 
        // Change head before proceeding
        node = curr;
 
        // Traverse the list
        while (true) {
            Node next = curr.next;
 
            // Change next of current as previous node
            curr.next = prev;
 
            // If next NULL or next is the last node
            if (next == null || next.next == null) {
                prev.next = next;
                break;
            }
 
            // Change next of previous to next of next
            prev.next = next.next;
 
            // Update previous and curr
            prev = next;
            curr = prev.next;
        }
        return node;
    }
 
    /* Function to print nodes
    in a given linked list */
    void printList(Node node)
    {
        while (node != null) {
            Console.Write(node.data + " ");
            node = node.next;
        }
    }
 
    // Driver code
    public static void Main(String[] args)
    {
 
        /* The constructed linked list is:
        1->2->3->4->5->6->7 */
        LinkedList list = new LinkedList();
        list.head = new Node(1);
        list.head.next = new Node(2);
        list.head.next.next = new Node(3);
        list.head.next.next.next = new Node(4);
        list.head.next.next.next.next = new Node(5);
        list.head.next.next.next.next.next = new Node(6);
        list.head.next.next.next.next.next.next = new Node(7);
 
        Console.WriteLine("Linked list before calling pairwiseSwap() ");
        list.printList(list.head);
        Node st = list.pairWiseSwap(list.head);
        Console.WriteLine("");
        Console.WriteLine("Linked list after calling pairwiseSwap() ");
        list.printList(st);
        Console.WriteLine("");
    }
}
 
// This code contributed by Rajput-Ji
 
 

Javascript




<script>
// javascript program to swap elements of linked list by changing links
var head;
 
     class Node {
            constructor(val) {
                this.data = val;
                this.next = null;
            }
        }
      
 
    /* Function to pairwise swap elements of a linked list */
    function pairWiseSwap(node) {
 
        // If linked list is empty or there is only one node in list
        if (node == null || node.next == null) {
            return node;
        }
 
        // Initialize previous and current pointers
        var prev = node;
        var curr = node.next;
 
        node = curr; // Change head before proceeding
 
        // Traverse the list
        while (true) {
        var next = curr.next;
            curr.next = prev; // Change next of current as previous node
 
            // If next NULL or next is the last node
            if (next == null || next.next == null) {
                prev.next = next;
                break;
            }
 
            // Change next of previous to next next
            prev.next = next.next;
 
            // Update previous and curr
            prev = next;
            curr = prev.next;
        }
        return node;
    }
 
    /* Function to print nodes in a given linked list */
    function printList(node) {
        while (node != null) {
            document.write(node.data + " ");
            node = node.next;
        }
    }
 
    // Driver program to test above functions
     
 
        /*
         * The constructed linked list is: 1->2->3->4->5->6->7
         */
        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);
        head.next.next.next.next.next.next = new Node(7);
 
        document.write("Linked list before calling pairwiseSwap() ");
        printList(head);
        var st = pairWiseSwap(head);
        document.write("<br/>");
        document.write("Linked list after calling pairwiseSwap() ");
        printList(st);
        document.write("");
 
// This code contributed by aashish1995
</script>
 
 
Output
Linked list before calling pairWiseSwap() 1 2 3 4 5 6 7  Linked list after callingpairWiseSwap() 2 1 4 3 6 5 7 

Time Complexity: The time complexity of the above program is O(n) where n is the number of nodes in a given linked list. The while loop does a traversal of the given linked list.
Auxiliary Space: O(1) since using constant space to track prev and next

Following is the recursive implementation of the same approach. We change the first two nodes and recur for the remaining list. Thanks to geek and omer salem for suggesting this method. 

Implementation:

C++




/* This program swaps the nodes of linked list rather than swapping the
field from the nodes.
Imagine a case where a node contains many fields, there will be plenty
of unnecessary swap calls. */
 
#include <bits/stdc++.h>
using namespace std;
 
/* A linked list node */
class node {
public:
    int data;
    node* next;
};
 
/* Function to pairwise swap elements of a linked list.
It returns head of the modified list, so return value
of this node must be assigned */
node* pairWiseSwap(node* head)
{
    // Base Case: The list is empty or has only one node
    if (head == NULL || head->next == NULL)
        return head;
 
    // Store head of list after two nodes
    node* remaining = head->next->next;
 
    // Change head
    node* newhead = head->next;
 
    // Change next of second node
    head->next->next = head;
 
    // Recur for remaining list and change next of head
    head->next = pairWiseSwap(remaining);
 
    // Return new head of modified list
    return newhead;
}
 
/* Function to add a node at the beginning of Linked List */
void push(node** head_ref, int new_data)
{
    /* allocate node */
    node* new_node = new node();
 
    /* put in the data */
    new_node->data = new_data;
 
    /* link the old list of the new node */
    new_node->next = (*head_ref);
 
    /* move the head to point to the new node */
    (*head_ref) = new_node;
}
 
/* Function to print nodes in a given linked list */
void printList(node* node)
{
    while (node != NULL) {
        cout << node->data << " ";
        node = node->next;
    }
}
 
/* Driver program to test above function */
int main()
{
    node* start = NULL;
 
    /* The constructed linked list is:
    1->2->3->4->5->6->7 */
    push(&start, 7);
    push(&start, 6);
    push(&start, 5);
    push(&start, 4);
    push(&start, 3);
    push(&start, 2);
    push(&start, 1);
 
    cout << "Linked list before calling pairWiseSwap() ";
    printList(start);
 
    start = pairWiseSwap(start); // NOTE THIS CHANGE
 
    cout << "\nLinked list after calling pairWiseSwap() ";
    printList(start);
 
    return 0;
}
 
// This is code is contributed by rathbhupendra
 
 

C




/* This program swaps the nodes of linked list rather than swapping the
field from the nodes.
Imagine a case where a node contains many fields, there will be plenty
of unnecessary swap calls. */
 
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
 
/* A linked list node */
struct node {
    int data;
    struct node* next;
};
 
/* Function to pairwise swap elements of a linked list.
   It returns head of the modified list, so return value
   of this node must be assigned */
struct node* pairWiseSwap(struct node* head)
{
    // Base Case: The list is empty or has only one node
    if (head == NULL || head->next == NULL)
        return head;
 
    // Store head of list after two nodes
    struct node* remaining = head->next->next;
 
    // Change head
    struct node* newhead = head->next;
 
    // Change next of second node
    head->next->next = head;
 
    // Recur for remaining list and change next of head
    head->next = pairWiseSwap(remaining);
 
    // Return new head of modified list
    return newhead;
}
 
/* Function to add a node at the beginning of Linked List */
void push(struct node** head_ref, int new_data)
{
    /* allocate node */
    struct node* new_node = (struct node*)malloc(sizeof(struct node));
 
    /* put in the data  */
    new_node->data = new_data;
 
    /* link the old list of the new node */
    new_node->next = (*head_ref);
 
    /* move the head to point to the new node */
    (*head_ref) = new_node;
}
 
/* Function to print nodes in a given linked list */
void printList(struct node* node)
{
    while (node != NULL) {
        printf("%d ", node->data);
        node = node->next;
    }
}
 
/* Driver program to test above function */
int main()
{
    struct node* start = NULL;
 
    /* The constructed linked list is:
     1->2->3->4->5->6->7 */
    push(&start, 7);
    push(&start, 6);
    push(&start, 5);
    push(&start, 4);
    push(&start, 3);
    push(&start, 2);
    push(&start, 1);
 
    printf("\n Linked list before calling  pairWiseSwap() ");
    printList(start);
 
    start = pairWiseSwap(start); // NOTE THIS CHANGE
 
    printf("\n Linked list after calling  pairWiseSwap() ");
    printList(start);
 
    return 0;
}
 
 

Java




// Java program to swap elements of linked list by changing links
 
class LinkedList {
 
    static Node head;
 
    static class Node {
 
        int data;
        Node next;
 
        Node(int d)
        {
            data = d;
            next = null;
        }
    }
 
    /* Function to pairwise swap elements of a linked list.
     It returns head of the modified list, so return value
     of this node must be assigned */
    Node pairWiseSwap(Node node)
    {
 
        // Base Case: The list is empty or has only one node
        if (node == null || node.next == null) {
            return node;
        }
 
        // Store head of list after two nodes
        Node remaining = node.next.next;
 
        // Change head
        Node newhead = node.next;
 
        // Change next of second node
        node.next.next = node;
 
        // Recur for remaining list and change next of head
        node.next = pairWiseSwap(remaining);
 
        // Return new head of modified list
        return newhead;
    }
 
    /* Function to print nodes in a given linked list */
    void printList(Node node)
    {
        while (node != null) {
            System.out.print(node.data + " ");
            node = node.next;
        }
    }
 
    // Driver program to test above functions
    public static void main(String[] args)
    {
 
        /* The constructed linked list is:
         1->2->3->4->5->6->7 */
        LinkedList list = new LinkedList();
        list.head = new Node(1);
        list.head.next = new Node(2);
        list.head.next.next = new Node(3);
        list.head.next.next.next = new Node(4);
        list.head.next.next.next.next = new Node(5);
        list.head.next.next.next.next.next = new Node(6);
        list.head.next.next.next.next.next.next = new Node(7);
 
        System.out.println("Linked list before calling pairwiseSwap() ");
        list.printList(head);
        head = list.pairWiseSwap(head);
        System.out.println("");
        System.out.println("Linked list after calling pairwiseSwap() ");
        list.printList(head);
        System.out.println("");
    }
}
 
 

Python3




# Python3 program to pairwise swap
# linked list using recursive method
 
# Linked List Node
class Node:
     
    def __init__(self, data):
         
        self.data = data
        self.next = None
 
# Create and Handle list operations
class LinkedList:
     
    def __init__(self):
         
        # Head of list
        self.head = None 
 
    # Add data to list
    def addToList(self, data):
         
        newNode = Node(data)
         
        if self.head is None:
            self.head = newNode
            return
 
        last = self.head
         
        while last.next:
            last = last.next
 
        last.next = newNode
 
    # Function to print nodes in
    # a given linked list
    def __str__(self):
         
        linkedListStr = ""
        temp = self.head
         
        while temp:
            linkedListStr = (linkedListStr +
                            str(temp.data) + " ")
            temp = temp.next
        return linkedListStr
 
    # Function to pairwise swap elements of
    # a linked list.It returns head of the
    # modified list, so return value
    # of this node must be assigned
    def pairWiseSwap(self, node):
 
        # If list is empty or with one node
        if node is None or node.next is None:
            return node
 
        # Store head of list after 2 nodes
        remaining = node.next.next
 
        # Change head
        newHead = node.next
 
        # Change next to second node
        node.next.next = node
 
        # Recur for remaining list and
        # change next of head
        node.next = self.pairWiseSwap(remaining)
 
        # Return new head of modified list
        return newHead
 
# Driver Code
linkedList = LinkedList()
linkedList.addToList(1)
linkedList.addToList(2)
linkedList.addToList(3)
linkedList.addToList(4)
linkedList.addToList(5)
linkedList.addToList(6)
linkedList.addToList(7)
 
print("Linked list before calling "
      "pairwiseSwap() ", linkedList)
       
linkedList.head = linkedList.pairWiseSwap(
    linkedList.head)
print("Linked list after calling "
      "pairwiseSwap() ", linkedList)
 
# This code is contributed by AmiyaRanjanRout
 
 

C#




// C# program to swap elements
// of linked list by changing links
using System;
 
public class LinkedList {
    Node head;
 
    class Node {
        public int data;
        public Node next;
 
        public Node(int d)
        {
            data = d;
            next = null;
        }
    }
 
    /* Function to pairwise swap
        elements of a linked list.
        It returns head of the modified
        list, so return value of this
        node must be assigned */
    Node pairWiseSwap(Node node)
    {
 
        // Base Case: The list is empty
        // or has only one node
        if (node == null || node.next == null) {
            return node;
        }
 
        // Store head of list after two nodes
        Node remaining = node.next.next;
 
        // Change head
        Node newhead = node.next;
 
        // Change next of second node
        node.next.next = node;
 
        // Recur for remaining list
        // and change next of head
        node.next = pairWiseSwap(remaining);
 
        // Return new head of modified list
        return newhead;
    }
 
    /* Function to print nodes in a given linked list */
    void printList(Node node)
    {
        while (node != null) {
            Console.Write(node.data + " ");
            node = node.next;
        }
    }
 
    // Driver program to test above functions
    public static void Main()
    {
 
        /* The constructed linked list is:
        1->2->3->4->5->6->7 */
        LinkedList list = new LinkedList();
        list.head = new Node(1);
        list.head.next = new Node(2);
        list.head.next.next = new Node(3);
        list.head.next.next.next = new Node(4);
        list.head.next.next.next.next = new Node(5);
        list.head.next.next.next.next.next = new Node(6);
        list.head.next.next.next.next.next.next = new Node(7);
 
        Console.WriteLine("Linked list before calling pairwiseSwap() ");
        list.printList(list.head);
        list.head = list.pairWiseSwap(list.head);
        Console.WriteLine("");
        Console.WriteLine("Linked list after calling pairwiseSwap() ");
        list.printList(list.head);
        Console.WriteLine("");
    }
}
 
// This code is contributed by PrinciRaj1992
 
 

Javascript




<script>
// javascript program to swap elements of linked list by changing links
var head;
 
     class Node {
            constructor(val) {
                this.data = val;
                this.next = null;
            }
        }
 
    /*
     * Function to pairwise swap elements of a linked  It returns head of the
     * modified list, so return value of this node must be assigned
     */
    function pairWiseSwap(node) {
 
        // Base Case: The list is empty or has only one node
        if (node == null || node.next == null) {
            return node;
        }
 
        // Store head of list after two nodes
var remaining = node.next.next;
 
        // Change head
var newhead = node.next;
 
        // Change next of second node
        node.next.next = node;
 
        // Recur for remaining list and change next of head
        node.next = pairWiseSwap(remaining);
 
        // Return new head of modified list
        return newhead;
    }
 
    /* Function to print nodes in a given linked list */
    function printList(node) {
        while (node != null) {
            document.write(node.data + " ");
            node = node.next;
        }
    }
 
    // Driver program to test above functions
     
 
        /*
         * The constructed linked list is: 1->2->3->4->5->6->7
         */
        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);
        head.next.next.next.next.next.next = new Node(7);
 
        document.write("Linked list before calling pairwiseSwap() ");
        printList(head);
        head = pairWiseSwap(head);
        document.write("<br/>");
        document.write("Linked list after calling pairwiseSwap() ");
        printList(head);
        document.write("");
 
// This code contributed by umadevi9616
</script>
 
 
Output
Linked list before calling pairWiseSwap() 1 2 3 4 5 6 7  Linked list after calling pairWiseSwap() 2 1 4 3 6 5 7 

Time Complexity: O(n)
Auxiliary Space: O(n)

Pairwise swap adjacent nodes of a linked list by changing pointers | Set 2



Next Article
Pairwise swap adjacent nodes of a linked list by changing pointers | Set 2
author
kartik
Improve
Article Tags :
  • DSA
  • Linked List
  • Linked Lists
Practice Tags :
  • 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
  • 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
  • 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
  • Pairwise Swap Elements of a given Linked List
    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
    13 min read
  • Print nodes of linked list at given indexes
    Given head of two singly linked lists, first one is sorted and the other one is unsorted. The task is to print the elements of the second linked list according to the position pointed out by the data in the first linked list. For example, if the first linked list is 1->2->5, then you have to p
    15+ min read
  • Segregate even and odd nodes in a Linked List
    Given a Linked List of integers, The task is to modify the linked list such that all even numbers appear before all the odd numbers in the modified linked list. Also, preserve the order of even and odd numbers. Examples: Input: 17->15->8->12->10->5->4->1->7->6->NULLOutp
    15+ min read
  • Pairwise Swap leaf nodes in a binary tree
    Given a binary tree, we need to write a program to swap leaf nodes in the given binary tree pairwise starting from left to right as shown below. Tree before swapping: Tree after swapping: The sequence of leaf nodes in original binary tree from left to right is (4, 6, 7, 9, 10). Now if we try to form
    11 min read
  • Left rotate Linked List by X in groups of Y nodes
    Given a singly linked list and two integers X and Y, the task is to left rotate the linked list by X in groups of Y nodes. Examples: Input: 10 -> 20 -> 30 -> 40 -> 50 -> 60 -> 70 -> 80 -> 90 -> 100, X = 2, Y = 4Output: 30 -> 40 -> 10 -> 20 -> 70 -> 80 ->
    10 min read
  • Reverse the order of all nodes at even position in given Linked List
    Given a linked list A[] of N integers, the task is to reverse the order of all integers at an even position. Examples: Input: A[] = 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> NULLOutput: 1 6 3 4 5 2Explanation: Nodes at even position in the given linked list are 2, 4 and 6. So, after reversing
    10 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
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