Open In App

C++ Program For Pairwise Swapping Elements Of A Given Linked List By Changing Links

Last Updated : 13 Feb, 2023
Improve
Improve
Like Article
Like
Save
Share
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. 

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;
  
    // Change head before proceeding
    head = 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 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);
 
    // NOTE THIS CHANGE
    start = pairWiseSwap(start);
 
    cout << "Linked list after calling" <<
            "pairWiseSwap() ";
    printList(start);
 
    return 0;
}
// This code is contributed by Manoj N


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

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. 

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);
 
    // NOTE THIS CHANGE
    start = pairWiseSwap(start);
 
    cout <<
    "Linked list after calling pairWiseSwap() ";
    printList(start);
 
    return 0;
}
// This code is contributed by rathbhupendra


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)

Please refer complete article on Pairwise swap elements of a given linked list by changing links for more details!



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads