[Data structure] use C ++ to write stacks and basic operations (including stack entry, stack exit, stack top acquisition, destruction, and clearing)

Source: Internet
Author: User

[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 () <
    
   
  
 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.