可直接编译运行,其中方法status为形象的显示出栈的结构:
1 // visual stack , need define "cout<<" 2 3 #include <iostream> 4 using std::cout; 5 6 template<typename T> 7 struct item 8 { 9 item():value(),last(NULL),next(NULL){} 10 item *last,*next; 11 T value; 12 }; 13 template<typename T> 14 class Stack 15 { 16 public: 17 Stack():m_size(0),m_bottom(NULL),m_top(NULL){} 18 int size(); 19 bool push(const T&); 20 T pop(); 21 T top(); 22 bool empty(); 23 void status(); 24 private: 25 item<T> *m_bottom,*m_top; 26 int m_size; 27 }; 28 29 30 /// 31 int main() 32 { 33 Stack<int> st; 34 for(int i=0;i<10;i++) 35 { 36 st.push(i); 37 st.status(); 38 } 39 cout<<"size="<<st.size()<<"\n"; 40 41 for( i=0;i<10;i++) 42 { 43 st.pop(); 44 st.status(); 45 } 46 if(st.empty())cout<<"empty\n"; 47 cout<<st.top()<<"\n"; 48 return 0; 49 } 50 51 52 //// 53 template<typename T> 54 inline int Stack<T>::size(){return m_size;} 55 56 template<typename T> 57 inline bool Stack<T>::empty(){return m_size==0?false:true;} 58 59 template<typename T> 60 inline T Stack<T>::top(){return m_size!=0?m_top->value:T();} 61 62 template<typename T> 63 bool Stack<T>::push(const T& t) 64 { 65 if(m_size==0) 66 { 67 m_bottom=new item<T>; 68 m_bottom->value=t; 69 m_top=m_bottom; 70 } 71 else 72 { 73 m_top->next=new item<T>; 74 m_top->next->value=t; 75 m_top->next->last=m_top; 76 m_top=m_top->next; 77 } 78 m_size++; 79 return true; 80 } 81 82 template<typename T> 83 T Stack<T>::pop() 84 { 85 if(m_size==1) 86 { 87 T t=m_top->value; 88 delete m_top; 89 m_bottom=m_top=NULL; 90 m_size=0; 91 return t; 92 } 93 else if(m_size==0) 94 { 95 return T(); 96 } 97 else 98 { 99 T t=m_top->value; 100 m_top=m_top->last; 101 delete m_top->next; 102 m_top->next=NULL; 103 m_size--; 104 return t; 105 } 106 return T(); 107 } 108 109 template<typename T> 110 void Stack<T>::status() 111 { 112 item<T> *p; 113 cout<<"栈顶 |\n"; 114 if( m_size==0 )return ; 115 else if(m_size<10) 116 { 117 for(p=m_top;p!=NULL;p=p->last) 118 { 119 if(p->last==NULL)cout<<"栈底 |"<<p->value<<"|\n"; 120 else cout<<" |"<<p->value<<"|\n"; 121 } 122 } 123 else 124 { 125 int i; 126 for(p=m_top,i=0;i<4;p=p->last,i++)cout<<" |"<<p->value<<"|\n"; 127 for(p=m_bottom,i=0;i<4;p=p->next,i++); 128 cout<<" 略...\n"; 129 for(;i>=0;i--,p=p->last) 130 { 131 if(i==0)cout<<"栈底 |"<<p->value<<"|\n"; 132 else cout<<" |"<<p->value<<"|\n"; 133 } 134 } 135 }