Q:

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

belongs to collection: C++ programs on various topics

0

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

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

C++ programs on various topics

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Convert a given binary Tree to Doubly Linked List ... >>
<< Reverse a Linked List in groups of given size usin...