Template to implement a general Stack
Template <class T, int size> class carraystacktemp
{
Public:
Carraystacktemp () // default constructor to construct an empty Stack
{
Top =-1;
};
~ Carraystacktemp () {}; // destructor
Void setempty (); // empty Stack
Bool isempty (); // determines whether the stack is empty.
Bool push (t element); // inbound Stack
Bool POP (T & element); // output Stack
PRIVATE:
T buffer [size];
Int top;
};
The implementation of member functions corresponding to the basic operations of the stack is as follows:
Template <class T, int size> void carraystacktemp <t, siz
E >:: setempty ()
{
Top =-1; // assign the top pointer of the stack to-1 without actually clearing array elements.
}
Template <class T, int size> bool carraystacktemp <t, siz
E >:: isempty ()
{
Return (Top =-1 );
}
Template <class T, int size> bool carraystacktemp <t, siz
E>: Push (t element)
{
Top ++;
If (top> size-1)
{
Top --;
Return false; // the stack is full and the inbound operation cannot be performed.
}
Buffer [Top] = element;
Return true;
}
Template <class T, int size> void carraystacktemp <t, siz
E>: Pop (T & element)
{
If (isempty ())
Return false;
Element = buffer [Top];
Top --;
Return true;
}
You can also expand the stack function as needed. For example, adding the elements to the top of the stack
Stack length and other operations, the method is as above.
Implementation of General Chain Stack
You can use pointers and define your own structures in the template class, which is used to implement the chain structure.
Guarantees. A single-chain table is used to implement the stack. The stack top Pointer Points to the linked list
At the first node, both the inbound and outbound stacks are performed at the head of the linked list. The template class is defined as follows:
Template <class T> class clinkstacktemp
{
Public:
// Default constructor of the class to generate an empty Stack
Clinkstacktemp ()
{
Top = NULL;
};
~ Clinkstacktemp () {}; // destructor
// Define the node Structure
Struct Node
{
T
Data; // The inbound stack Element
Node * Next; // pointer to the next node
};
Void setempty (); // empty Stack
Bool isempty (); // determines whether the stack is empty.
Bool push (t element); // push to stack
Bool POP (T & element); // pop up the stack
PRIVATE:
Node * top;
};
The member functions of this class are implemented as follows:
Template <class T> void clinkstacktemp <t>: setempty ()
{
// Release the memory occupied by the stack
Node * temp;
While (top! = NULL)
{
Temp = top;
Top = Top-> next;
Delete temp;
}
}
Template <class T> bool clinkstacktemp <t>: isempty ()
{
Return (Top = NULL );
}
Template <class T> bool clinkstacktemp <t>: Push (t element)
{
Node * temp = new node ();
If (temp = NULL)
Return false;
Temp-> DATA = element;
Temp-> next = top;
Top = temp;
Return true;
}
Template <class T> bool clinkstacktemp <t>: Pop (T & element)
{
If (isempty ())
Return false;
Node * q = top;
Element = Top-> data;
Top = Top-> next;
Delete Q;
Return true;
}