Swap the nth and the mth node in a linked list

In this case n = 2 and m = 4.
Please give a linked list of size > 4. Corner cases are not handled. Only the main swapping part is handled.

 

#include <iostream>
#include <algorithm>
#include <cstdlib>

using namespace std;

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

node *allocate(){
node *ptr = (node *)malloc(sizeof(node));
ptr -> next = NULL;
return ptr;
}

node *f(){
int x;
cin >> x;
if(x == -1)
return NULL;
node *head = allocate();
head ->data = x;
head ->next = f();
return head;
}

int main()
{
cout << "Enter items of list:-\nType -1 to exit.\n";
node *head;
head = NULL;
head = f();
node *temp = head;
while(temp!= NULL)
cout << temp->data << " ", temp = temp->next;
node *ptr2, *ptr4;
temp = head;
for(int i = 0; i < 4; i++){
if(i == 0)
ptr2 = temp;
else if(i == 2)
ptr4 = temp;
temp = temp -> next;
}

// cout << ptr2->data << " " << ptr4->data << endl;
temp = (ptr2->next) -> next;
ptr2->next->next = ptr4->next->next;
ptr4->next->next = temp;

temp = ptr2->next;
ptr2->next = ptr4->next;
ptr4->next = temp;
cout << endl;
temp = head;
// system ("pause");
while(temp!= NULL)
cout << temp->data << " ", temp = temp->next;

return 0;
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s