[Data structure] use C ++ to write stacks and basic operations (including stack entry, stack exit, stack top acquisition, destruction, and clearing)
// [Data structure] use C ++ to write stacks and basic operations (including inbound, outbound, stack top, destroy, and empty) // header file # ifndef _ SEQ_STACK _ # define _ SEQ_STACK _ # include
Using namespace std; template
Class SeqStack {public: SeqStack (size_t sz = INIT_SIZE) {capacity = sz> INIT_SIZE? Sz: INIT_SIZE; base = new Type [capacity]; top = 0 ;}~ SeqStack () {destory ();} public: bool empty () const // determine whether it is null {return (top = 0);} bool full () const // determine whether it is full {return (top> = capacity);} void push (const Type & x) // stack into {if (full ()) {cout <"the stack is full and cannot be inserted. "<Endl; return;} base [top ++] = x;} void pop () // output stack {top --;} bool getTop (Type & x) const // obtain the top stack {if (top = 0) return false; x = base [top-1]; return true;} int length () const // calculate the size {return top;} void clear () // clear {top = 0;} void destory () // destroy {delete [] base; base = NULL; capacity = top = 0;} void show () const // display {if (empty () = 1) {cout <"Stack is empty" <endl; return ;}for (int I = top-1; I >=0; I --) {cout <base [I] <
Mystack; int select = 1; int Item; while (select) {cout <"*********************************** * ** "<endl; cout <"* [1] show [2] push *" <endl; cout <"* [3] pop [4] length *" <endl; cout <"* [5] clear [6] destory *" <endl; cout <"************************************ ** "<endl; cout <"select:>"; cin> select; switch (select) {case 1: mystack. show (); break; case 2: cout <"Enter the value to be inserted (-1):>"; while ( Cin> Item, Item! =-1) {mystack. push (Item) ;}break; case 3: mystack. pop (); break; case 4: cout <"Size:" <mystack. length () <