Home » C++ programs » D.S. programs

Pair wise swap elements in a linked list using C++ program

In this article, we discuss how to pair wise swap elements in a linked list? This article contains problem statement, explanation, algorithm, C++ implementation and output.
Submitted by Souvik Saha, on May 06, 2019

Given a singly linked list, write a function to swap elements pairwise.

Explanation and example:

If a linked list is 1 → 2 → 3 → 4 → 5 
Then the output will be: 2 → 1 → 4 → 3 → 5
If the linked list is 1 → 2 → 3 → 4 → 5 → 6 
Then the output will be: 2 → 1 → 4 → 3 → 6 → 5

Algorithm:

To solve this problem we firstly iterate the list from the head and take two consecutive nodes from that and swap the key values of them. Go for next two consecutive nodes. If there is only one node left then keep it same.

while (curr is not NULL  &&curr->next is not NULL)
    temp=curr->data;
    curr->data=curr->next->data;
    curr->next->data=temp;
    curr=curr->next->next;
End While

C++ implementation:

#include <bits/stdc++.h>
using namespace std;

struct node{
    int data;
    node* next;
};

//Create a new node
struct node* create_node(int x){
    struct node* temp= new node;
    temp->data=x;
    temp->next=NULL;
    return temp;
}

//Enter the node into the linked list
void push(node** head,int x){
    struct node* store=create_node(x);
    if(*head==NULL){
        *head =store;
        return;
    }
    struct node* temp=*head;
    while(temp->next){
        temp=temp->next;
    }
    temp->next=store;
}

//Reverse the linked list
struct node* swap(node* head){
	if(head==NULL){
		return NULL;
	}
	struct node* curr=head;
	while(curr && curr->next){
        int temp=curr->data;
        curr->data=curr->next->data;
        curr->next->data=temp;
        curr=curr->next->next;
	}
    return head;
}

//Print the list
void print(node* head){
	struct node* temp=head;
	while(temp){
		cout<<temp->data<<" ";
		temp=temp->next;
	}
}

int main()
{
    struct node* l=NULL;
    push(&l,1);
    push(&l,2);
    push(&l,3);
    push(&l,4);
    push(&l,5);
    push(&l,6);
    cout<<"Before the swap operation"<<endl;
    print(l);
    l=swap(l);
    cout<<"\nAfter the swap operation"<<endl;
    print(l);
	
    return 0;
}

Output

Before the swap operation
1 2 3 4 5 6
After the swap operation
2 1 4 3 6 5
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT


Top MCQs

Comments and Discussions!




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.