Data Structure-c ++ code for some basic stack operations
Stack (stack for short) is a linear table with limited operations. It only allows insert and delete operations on the same end of the table, and these operations are performed in accordance with the principle of advanced and later.
Template
Struct SLNode {T data; // data domain SLNode
* Next; // SLNode pointer domain (SLNode * nextNode = NULL) // constructor {next = nextNode;} SLNode (const T & item, SLNode * nextNode = NULL) // constructor {data = item; next = nextNode ;}}; // ordered stack template
Class AStack {public: AStack (int MaxStackSize) // constructor {size = MaxStackSize; stackArray = new T [MaxStackSize]; top =-1 ;}~ AStack () // destructor {delete [] stackArray;} bool Push (const T & item) // press an element to the top of the stack {if (IsFull ()) {cout <"Pushing into a full stack! "<Endl; return false;} stackArray [++ top] = item; return true;} bool Pop (T & item) // an element {if (IsEmpty () {cout <"Poping from an empty stack! "<Endl; return false;} item = stackArray [top --]; return true;} bool Peek (T & item) const // The top element of the access stack {if (IsEmpty () {cout <"Peeking from an empty stack! "<Endl; return false;} item = stackArray [top]; return true;} int IsEmpty () const // check whether the stack is empty {return top =-1;} int IsFull () const // check whether the stack is full {return top = size-1 ;} void clear () // clear the stack {top =-1;} private: int size; // the size of the array T * stackArray; // The array int top that stores the stack elements; // subscript of the array element at the top of the stack}; // defines and implements the template of the chain stack LStack.
Class LStack {public: LStack () // constructor {top = NULL ;}~ LStack () // destructor {clear ();} void clear () // clear the stack {SLNode
* Temp; while (! IsEmpty () {temp = top-> next; delete top; top = temp ;}} bool Push (const T & item) // press an element {top = new SLNode to the top of the stack.
(Item, top); return true;} bool Pop (T & item) // an element pops up from the top of the stack {if (IsEmpty ()) {cout <"Poping from an empty stack! "<Endl; return false;} item = top-> data; SLNode
* Temp = top; top = top-> next;} bool Peek (T & item) const // read the top element of the stack {if (IsEmpty ()) {cout <"Poping from an empty stack! "<Endl; return false;} item = top-> data; return true;} int IsEmpty () const {return top = NULL;} private: SLNode
* Top ;};