Reverse a linked list in pairs


#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;
}

node *rev(node *head){
if(head == NULL || head->next == NULL)
return head;
node *A = head;
node *B = head -> next;
node *C = head;
A->next = B->next;
A = B;
B -> next = C;
head = B;
head -> next -> next = rev(head ->next ->next);
return B;
}

int main()
{
cout << "Enter items of list:-\nType -1 to exit.\n";
node *head;
head = NULL;
head = f();
node *temp = head;
cout << "The original list is\n";
while(temp!= NULL)
cout << temp->data << " ", temp = temp->next;
head = rev(head);
cout << endl;
temp = head;
cout << "The pairwise reversed list is\n";
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