i am writing a code for a stack within stack...or nested stack...whatever..
in the code..and the mainstack is a stack of substack, which in turn, is a stack of integer data..
i thought of using class template for both the stacks - mainstack and substack..but am confused with how to use it..
the code for the template is as under :
template <class T>
class stack
{
private :
struct node
{
T element;
node *link;
} *top;
public :
stack();
~stack();
void push (T ele);
T pop();
void view();
};
template <class T>
stack<T> :: stack()
{
top = NULL;
}
template <class T>
stack<T> :: ~stack()
{
node *destroy;
while ( top != NULL)
{
destroy = top;
top = top -> link;
delete destroy;
}
}
template <class T>
void stack<T> :: push (T ele)
{
node *newnode;
newnode = new node;
if (newnode == NULL)
{
cout << "Stack overflow!" << endl;
return;
}
newnode -> element = ele;
newnode -> link = top;
top = newnode;
}
template <class T>
T stack<T> :: pop()
{
if (top == NULL)
{
cout << "Stack is empty." << endl;
return NULL;
}
T popped;
popped = top->element;
node *temp;
temp = top;
top = top -> link;
delete temp;
return popped;
}
template <class T>
void stack<T> :: view()
{
node *temp = top;
while (temp != NULL)
{
cout << temp->element << endl;
temp = temp -> link;
}
}
however my problem is how do i define the mainstack in main()?
it may be something like this :
// declaring an object of "mainstack" type
stack <substack> S;
where substack is the substack..but then how do i define substack class??
should it be like this ??
// if i dont define a mainstack class
class substack
{
private :
stack <int> s;
public :
//overloaded operaters << and >> and constructors ...blah..blah...
};
but i think this is not a proper way to work with...
another way i thought to work is to define class mainstack something like this :
// if i dont define a substack class
class mainstack
{
private :
stack <int> s;
};
but then here the template wont work properly...i am much confused here...
anyone there to guide me..???? waiting for helpful replies....