Reverse a linked list


#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 **curr, node *last){
if((*curr)->next == NULL){
(*curr)->next = last;
return (*curr);
}
node *temp = rev(&((*curr)->next), *curr);
if(last != NULL)
(*curr)->next = last;
else
(*curr)->next = NULL;
return temp;
}

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