容器适配器实现栈Stack的各种功能:
我们知道,顺序表的特点是:相对比于链表插入和删除数据方便,无需像链表一样遍历来访问。因此,我们用容器适配器选择顺序表的模型来实现栈的各种功能。
#include<iostream> using namespace std; #include<assert.h> template<class T> class SeqList { private: T* _array; size_t _size; size_t _capacity; public: SeqList() :_array(NULL) , _size(0) , _capacity(0) {} SeqList(const SeqList<T>& s) { _array = new T[s._size]; for (size_t i = 0; i < s._size; i++) { _array[i] = s._array[i]; } _size = s._size; _capacity = s._size; } SeqList<T>& operator=(SeqList<T> s) { if (&s != this) { swap(_array, s._array); swap(_size, s._size); swap(_capacity, s._capacity); } return *this; } ~SeqList() { if (_array) { delete[] _array; } } //扩容 void _CheckCapacity(size_t n) { if (n > _capacity) { _capacity = n > 2 * _capacity + 3 ? n : 2 * _capacity + 3; T* tmp = new T[_capacity]; if (_array) { for (size_t i = 0; i < _size; i++) { tmp[i] = _array[i]; } } delete[] _array; _array = tmp; } } int Size() { return _size; } //打印 void PrintSeqList() { for (size_t i = 0; i < _size; i++) { cout << _array[i] << " "; } cout << endl; } //尾插 void PushBack(const T& x) { _CheckCapacity(_size + 1); _array[_size++] = x; } //尾删 void PopBack() { if (_size == 0) { return; } else { --_size; } } //operator[] T& operator[](size_t index) { /*assert(index < _size);*/ return _array[index]; } //请求空间 void Reserve(size_t n) { _CheckCapacity(n); } }; template<class T, template<class> class Container = SeqList> class Stack { public: //入栈 void Push(const T& x) { _con.PushBack(x); } //出栈 void Pop() { _con.PopBack(); } //大小 size_t Size() { return _con.Size(); } //判空 bool Empty() { return _con.Size() == 0; } //栈顶 T& Top() { size_t size = _con.Size(); assert(size > 0); return _con[size - 1]; } protected: Container<T> _con; }; void TestStack() { Stack<int> ss1; ss1.Push(1); ss1.Push(2); ss1.Push(3); ss1.Push(4); ss1.Push(5); //访问栈中所有元素 while (!ss1.Empty()) { cout << ss1.Top()<< " "; ss1.Pop(); } } int main() { TestStack(); system("pause"); return 0; }