静态栈:
#include<iostream> #include<assert.h> using namespace std; template <class T,size_t N=100> class Stack//栈顶插入,删除 因此适合用顺序表 //静态 { public: void Push(const T&x) { if (_size == N) { throw out_of_range("out of range");//如果空间不够,抛异常 } _a[size++] = x; } void Pop() { assert(_size > 0); --_size; } T& Top() { assert(_size > 0); return _a[_size - 1]; } private: T _a[N]; size_t _size; };
动态栈:
template<class T> class Stack { public: Stack() :_a(NULL) , _size(0) , _capacity(0) {}; void Push(const T& x) { CheckCapacity(); _a[_size] = x; _size++; } void Pop() { if (_size <= 0) return; --_size; } T Top() { assert(_size > 0); return _a[_size-1]; } void CheckCapacity() { if (_size >= _capacity) { size_t capacity = _capacity * 2 + 3; T* tmp = new T[capacity];//开空间 注意此处T类型不确定,可能为自定义类型 因此不能用realloc开空间 for (size_t i = 0; i < _size; i++) { tmp[i] = _a[i]; } delete[] _a; _a = tmp; _capacity = capacity; } } size_t Size() { return _size; } bool Empty() { return (_size == 0); } private: T* _a; size_t _size; size_t _capacity; }; void TestStack() { Stack<int> s1; s1.Push(1); s1.Push(2); s1.Push(3); s1.Push(4); int size = s1.Size(); for (size_t i = 0; i <size; i++) { cout << s1.Top() <<" "; s1.Pop(); } cout << endl; /*s1.Pop(); s1.Pop(); for (size_t i = 0; i < s1.Size(); i++) { cout << s1.Top() << " "; s1.Pop(); }*/ cout << endl; } int main() { TestStack(); system("pause"); return 0; }
队列:
#include<iostream> using namespace std; template<class T> struct QueueNode { T _data; QueueNode<T>* _next; QueueNode(const T& x) :_data(x) ,_next(NULL) {} }; template <class T> class Queue { public: Queue() :_head(NULL) , _tail(NULL) {} typedef QueueNode<T> Node; void Push(const T& x) { Node* tmp = new Node(x); if (_head == NULL) { _tail= _head = tmp; } else { _tail->_next = tmp; _tail = tmp; } } void Pop() { //三种情况 if (_head == NULL) { return; } else if (_head == _tail) { _head = _tail = NULL; } else { Node* next = _head->_next; delete _head; _head = next; } } T& Front() { if (_head != NULL) { return _head->_data; } } bool Empty() { return _head == NULL; } size_t Size() { size_t count = 0; Node *tmp = _head; while (tmp) { count++; tmp = tmp->_next; } return count; } private: Node* _tail; Node* _head; }; void TestQueue() { Queue<int> q1; q1.Push(1); q1.Push(2); q1.Push(4); q1.Push(5); /*while (!q1.Empty())//方法二 时间复杂度为O(N^2) { cout << q1.Front() << " "; q1.Pop(); } cout << endl;*/ while ( !q1.Empty())//方法一 时间复杂度为O(N) 因此在链表中,应该少用Size().因为它把链表遍历了一遍时间复杂度为0(N) { cout << q1.Front() << " "; q1.Pop(); } cout << endl; } int main() { TestQueue(); system("pause"); return 0; }