标签:栈
//栈的特点:后进先出,只能从尾部进行操作
//Stack.h #pragma once #include<iostream> #include<assert.h> #include<string> using namespace std; template<class T> class Stack { public: Stack() :_array(NULL) , _size(0) , _capacity(0) {} Stack(const Stack<T>& s) :_array(new T[s._capacity]) , _size(s._size) , _capacity(s._capacity) { for (int i = 0; i < s._size; ++i) { _array[i] = s._array[i]; } } Stack& operator=(Stack s) { swap(_array, s._array); swap(_size, s._size); swap(_capacity, s._capacity); return *this; } ~Stack() { delete[] _array; _size = _capacity = 0; } void Push(const T& x) { _CheckCapacity(); _array[_size++] = x; } void Pop() { assert(_size > 0); _size--; } bool IsEmpty() { return _size == 0; } bool IsFull() { return _size == _capacity; } size_t Size() { return _size; } const T& Top() { return _array[_size - 1]; } protected: void _CheckCapacity() { if (_size == _capacity) { _capacity = 2 * _capacity + 3; T* tmp= new T[_capacity]; if (_array) { for (int i = 0; i < _size; ++i) { tmp[i] = _array[i]; } delete[] _array; } _array = tmp; } } protected: T *_array; size_t _size; size_t _capacity; }; void TestStack() { Stack<int> s1; s1.Push(1); s1.Push(2); s1.Push(3); s1.Push(4); s1.Push(5); s1.Push(6); //打印栈 while (!s1.IsEmpty()) { cout << s1.Top()<<" "; s1.Pop(); } cout << endl; } void TestStack1() { Stack<string> s2; s2.Push("ab"); s2.Push("cd"); s2.Push("ef"); s2.Push("gh"); s2.Push("lm"); s2.Push("nw"); while (!s2.IsEmpty()) { cout << s2.Top() << " "; s2.Pop(); } cout << endl; } //Test.cpp #include<iostream> using namespace std; #include"Stack.h" int main() { TestStack1(); system("pause"); return 0; }
本文出自 “小止” 博客,请务必保留此出处http://10541556.blog.51cto.com/10531556/1730846
标签:栈
原文地址:http://10541556.blog.51cto.com/10531556/1730846