In our software development, the important data structure of stack is often used. Stack is an advanced linear structure. We have seen many examples written online, all are based on the basic data type. In our actual development, most of them are based on specific types. We cannot write a version for each type of data, which is so tired, poor scalability, so you must use a template to implement it.
The following is the implementationCode, There are poor and imperfect writing, and we will discuss it together:
# Pragma once # include <stdlib. h> template <class etype> class Stack {public: Stack (void );~ Stack (void); int push (const etype & E); // push elements into the stack int POP (etype & E); // push the top elements of the stack out of the stack int isempty () const // determine whether the stack is empty {return Top =-1;} int isfull () const // determine whether the stack is full {return Top = size-1 ;} etype operator [] (INT index); int size () const {return top + 1;} etype * getdata () const; // obtain data private: int size; // number of elements int top; // stack top pointer etype * stackptr; // pointer to the top element of the stack}; // defines part of the template <class etype> stack <etype>:: Stack (void) {size = 100; Top =-1; ST Ackptr = new etype [size];} template <class etype> stack <etype> ::~ Stack (void) {Delete [] stackptr;} template <class etype> int stack <etype >:: push (const etype & E) {// If the stack is full, then the append space if (isfull () {stackptr = (etype *) realloc (stackptr, (size + 10) * sizeof (etype )); stackptr [++ top] = E; size + = 10; // The capacity is also increased by 10 return 1;} else {stackptr [++ top] = E; return 1 ;} return 0;} template <class etype> int stack <etype>: Pop (etype & E) {If (! Isempty () {e = stackptr [top --]; return 1;} return 0;} template <class etype> etype stack <etype >:: operator [] (INT index) {return stackptr [Index];} template <class etype> etype * stack <etype >:: getdata () const {return stackptr ;}
in this way, I can use this code every time. I don't need to change it.