/* C++ program for Linked List using Template */
#include<iostream.h>
#include<stdlib.h>
template <class T>
class list
{
struct node
{
T data;
struct node *link;
}*start;
public: void create_list(T);
void traverse();
void reverse();
list()
{
start=NULL;
}
~list()
{}
};
template <class T>
void list<T>::create_list(T value)
{
struct node *temp,*p;
temp=new node;
temp->data=value;
temp->link=NULL;
if(start==NULL)
start=temp;
else
{
p=start;
while(p->link!=NULL)
p=p->link;
p->link=temp;
}
}
template <class T>
void list<T>::traverse()
{
struct node *p;
p=start;
if(p==NULL)
cout<<"\nList is empty";
else
for(p=start;p!=NULL;p=p->link)
cout<<p->data<<"\t";
}
template <class T>
void list<T>::reverse()
{
if(start==NULL)
cout<<"\nList is empty";
else if(start->link==NULL)
cout<<"\nList contains single node";
else
{
struct node *p1,*p2,*p3;
p1=start;
p2=p1->link;
p3=p2->link;
p1->link=NULL;
p2->link=p1;
while(p3!=NULL)
{
p1=p2;
p2=p3;
p3=p3->link;
p2->link=p1;
}
start=p2;
cout<<"\nList is reversed successfully";
}
}
int main()
{
list<int> l;
cout<<"\t\t____ SINGLY LINKED LIST ____";
while(1)
{
cout<<"\n1.Create list\t2.Traverse\t3.Reverse\t4.Exit";
cout<<"\n\tEnter choice: ";
int ch;
cin>>ch;
switch(ch)
{
case 1: cout<<"\nEnter value to insert :";
int value;
cin>>value;
l.create_list(value);
break;
case 2: l.traverse();
break;
case 3: l.reverse();
break;
case 4: return (0);
default: cout<<"\nERROR: Wrong choice";
}
}
}
No comments:
Post a Comment