Hi,
I wrote the following program for stacks using linked list! But, the display function doesn't seem to work!
can anyone point out the errors in this?
Thankyou!
#include <iostream>
#include <cstdlib>
#include <iomanip>
using namespace std;
template <class T>
class stack
{
T data;
stack<T> *top;
stack<T> *next;
public:
stack()
{
top = NULL;
next = NULL;
}
void push();
void pop();
void display();
};
template <class T>
void stack<T> :: push()
{
T elepu;
stack<T> *temp = new stack;
cout<<"Enter the element to be pushed: ";
cin>>elepu;
temp -> data = elepu;
if(top == NULL)
{
top = temp;
top -> next = NULL;
}
else
{
top -> next = temp;
top = temp;
top -> next = NULL;
}
cout<<endl<<"Element pushed!"<<endl;
}
template <class T>
void stack<T> :: pop()
{
stack<T> *temp = new stack;
temp = top;
if(top == NULL)
{
cout<<"Stack Underflow"<<endl;
}
else
{
temp -> data = top -> data;
top = top -> next;
delete temp;
}
cout<<endl<<"Element popped!"<<endl;
}
template <class T>
void stack<T> :: display()
{
cout<<"Elements in stack are: "<<endl;
stack<T> *temp = new stack;
temp = top;
if(top == NULL)
{
cout<<"Stack is Empty";
}
else
{
while(temp -> next != NULL)
{
cout<<temp -> data<<setw(6);
temp = temp -> next;
}
}
}
int main()
{
char choice;
stack<int> S;
while(1)
{
cout<<setw(6)<<"MENU"<<endl<<" ^^^^^"<<endl
<<" [1] PUSH"<<endl
<<" [2] POP"<<endl
<<" [3] DISPLAY"<<endl
<<" [4] EXIT"<<endl;
cout<<"\nENTER YOUR CHOICE: ";
cin>>choice;
switch(choice)
{
case '1': S.push(); break;
case '2': S.pop(); break;
case '3': S.display(); break;
case '4': exit(0); break;
default: cout<<"Not a valid entry!!" ; break;
}
cout<<endl<<"Do you wish to continue? (Y/N) ";
if(cin.get() == 'Y' || cin.get() == 'y')
continue;
else
break;
}
cin.ignore();
cin.get();
return 0;
}