20130330

How to write cpp program to reverse a linked list



//C++ program for reversing single Linked list nodes 
Cpp program for implement reversing Single Linked List
Single linked list program for reversing the nodes
How to reverse linked list 
#include<iostream>
using namespace std;

struct node
{
node *next;
int data;
};
class ll
{
private:
node *start;
public:
ll(){start=NULL;}

void insert(int a)
{
cout<<"Inside Insert."<<endl;
node *newnode=new node;
newnode->data=a;
newnode->next=start;
start=newnode;
//return;
}
void display();
void del();
void reverse();
};

//void ll::insert(int a){data=a;}
void ll::display()
{
cout<<"Inside display."<<endl;
node *curr=new node;
curr=start;
while(curr!=NULL)
{
cout<<curr->data<<" ";
curr=curr->next;
}
cout<<endl;
}
void ll::del()
{
cout<<"Inside del."<<endl;
node *temp=new node;
temp=start;
start=start->next;
delete temp;
}
void ll::reverse()
{
cout<<"Inside reverse."<<endl;

node *next=new node; next=NULL;
node *result=new node; result=NULL;
node *current=new node;current=start;

while(current!=NULL)
{
next=current->next;
current->next=result;
result=current;
current=next;
}
start=result;
}

int main()
{
ll l;
l.insert(10);
l.insert(20);
l.insert(30);
l.insert(40);
l.display();
l.reverse();
l.display();

l.del();
l.display();
return 0;
}
/* Inside Insert.
Inside Insert.
Inside Insert.
Inside Insert.
Inside display.
40 30 20 10
Inside reverse.
Inside display.
10 20 30 40
Inside del.
Inside display.
20 30 40
*/
Previous                             Home                               Next

No comments:

Post a Comment