标签:stack
栈提供了以下操作:
/*cpp*/ s.empty() //如果栈为空返回true,否则返回false s.size() //返回栈中元素个数 s.pop() //删除栈顶元素,但不返回其值 s.top() //返回栈顶元素,但不删除元素 s.push() //在栈顶压入新元素
模拟实现:
/*Stack.cpp*/ #include <iostream> using namespace std; template <class T> class SeqList { public: SeqList() :_data(NULL) ,_size(0) ,_capacity(0) { CheckCapacity(); } ~SeqList() { if(_data != NULL) { delete[] _data; } } public: void Display() const { int i = 0; for(i; i<_size; i++) { cout<<_data[i]<<" "; } cout<<"over"<<endl; } void CheckCapacity() { if(_size == _capacity) { T* tmp = new T[_capacity+3]; memcpy(tmp, _data, (_capacity)*sizeof(T)); delete[] _data; _data = tmp; _capacity = _capacity+3; } } void PushBack(const T& d) { CheckCapacity(); _data[_size] = d; _size++; } void PopBack() { if(_size == 0) { cout<<"Stack is empty!!"<<endl; return; } _size--; } int GetSize() { return _size; } T& retTop() const { if(_data == NULL) { cout<<"Stack is empty!!"<<endl; exit(1); } return _data[_size-1]; } bool retEmpty() const { if(_data == NULL) { return false; } return true; } protected: int _size ; int _capacity ; T* _data ; }; template <class T, class Container > class Stack { public : void Push(const T& x) { _con.PushBack(x); } void Pop() { _con.PopBack(); } int Size() { return _con.GetSize(); } const T& Top() { return _con.retTop(); } bool Empty() { return _con.retEmpty(); } void Show() { _con.Display(); } private: Container _con; }; int main() { Stack<int, SeqList<int>> stack1; stack1.Push(1); stack1.Push(2); stack1.Push(3); stack1.Push(4); stack1.Push(5); stack1.Show(); stack1.Pop(); stack1.Show(); int ret = stack1.Top(); cout<<ret<<endl; bool result = stack1.Empty(); cout<<result<<endl; int size = stack1.Size(); cout<<size<<endl; system("pause"); return 0; }
结果:
本文出自 “Pzd流川枫” 博客,请务必保留此出处http://xujiafan.blog.51cto.com/10778767/1758086
标签:stack
原文地址:http://xujiafan.blog.51cto.com/10778767/1758086