栈的基本操作(C++)


栈的基本操作(C++)

  1. #include<iostream>  
  2. #include<stdlib.h>  
  3. using namespace std; 
  4. template <class elemtype> 
  5. class stack { 
  6.     public
  7.         virtual bool is_empty() const = 0; 
  8.         virtual void push(const elemtype &x) = 0; 
  9.         virtual elemtype pop() = 0; 
  10.         virtual elemtype top() const = 0; 
  11.         virtual ~stack() {} 
  12. }; 
  13.  
  14. template <class elemtype> 
  15. class set_stack: public stack <elemtype> { 
  16.     private
  17.         elemtype *elem; 
  18.         int top_p; 
  19.         int max_size; 
  20.         void double_space(); 
  21.     public
  22.         set_stack(int init_size = 10) { 
  23.             elem = new elemtype [init_size]; 
  24.             max_size = init_size; 
  25.             top_p = -1; 
  26.         } 
  27.         ~set_stack() { delete[] elem; } 
  28.         bool is_empty() const { return top_p == -1; } 
  29.         void push(const elemtype &x) { 
  30.             if(top_p == max_size - 1) { 
  31.                 double_space(); 
  32.             } 
  33.             elem[++top_p] = x; 
  34.         } 
  35.         elemtype pop() { 
  36.             return elem[--top_p]; 
  37.         } 
  38.         elemtype top() const { 
  39.             return elem[top_p]; 
  40.         } 
  41. }; 
  42.  
  43. template <class elemtype> 
  44. void set_stack<elemtype>::double_space(){ 
  45.     elemtype *tmp = elem; 
  46.     elem = new elemtype[2*max_size]; 
  47.     for(int i = 0; i < max_size; ++i) { 
  48.         elem[i] = tmp[i]; 
  49.     } 
  50.     max_size *= 2; 
  51.     delete[] tmp; 
  52. }; 
  53.  
  54.  
  55. int main() 
  56.     set_stack<int> *s = new set_stack<int>(10); 
  57.     cout<<s->is_empty(); 
  58.    // s->push(3);  
  59.    for(int i = 1; i <= 20; i++) { 
  60.        s->push(i*10); 
  61.    } 
  62.    for(int i = 1; i <=20 ; i++) { 
  63.       cout << s->top() << endl; 
  64.       s->pop(); 
  65.    } 
  66.     cout<<s->top(); 
  67.     return 0; 
  68. //这道题目的意义重大,标志我要全面学习C++了!呵呵,加油。 

相关内容