/*
Write a function to reverse a linked list. No double pointers please.
*/
#include
using namespace std;
struct node{int data; struct node *next;};
struct node* createlist()
{
int counter=0;
node *first, *temp, *last;
first = (node*)malloc(sizeof(node));
temp=first;
cin>>temp->data;
cout<<"Please enter the number of elements in the list that you want: ";
cin>>counter;
while(counter!=0)
{
temp->next=(node*)malloc(sizeof(node));
cout<<"Enter node data: ";
cin>>temp->data;
last=temp;
temp=temp->next;
counter–;
}
last->next =NULL;
delete(temp);
return first;
}
void display(struct node *header)
{
node *ptr;
ptr=header;
cout<<"The list now looks like: ";
while(ptr!=NULL)
{
cout<data<<" ";
ptr=ptr->next;
}
cout<<endl;
}
int lenlist(struct node *header)
{
node *ptr;
int len=0;
ptr=header;
while(ptr->next!=NULL)
{
len=len+1;
ptr=ptr->next;
};
return len;
}
struct node* reverselist(struct node *header)
{
int counter=5, tempHolder=0;
node *temp, *ptr,*prev, *last;
prev=NULL;
ptr=header;
//Obtain the length of the linked list
counter=lenlist(header);
while(counter!=0)
{
while(ptr->next!=NULL && ptr!=last)
{
if(ptr!=NULL)
{
tempHolder=ptr->data;
ptr->data=(ptr->next)->data;
(ptr->next)->data=tempHolder;
prev=ptr;
}
else
{
cout<<"IF YOU SEE THIS, THE CODE IS FAULTY. The value of ptr is NULL for counter value "<<counter<<endl;
}
ptr=ptr->next;
};
ptr=header;
last=prev;
counter–;
}
return header;
}
void main()
{
node *header, *latest;
node *header1;
header=createlist();
display(header);
latest=reverselist(header);
display(latest);
}