栈和队列

来源:互联网 发布:unity3d path 编辑:程序博客网 时间:2024/06/10 22:15


#include<iostream>using namespace std;//栈先进后出   //队列先进先出  template <typename T>class stack{public:stack():_arr(NULL), _size(0), _capacity(5){/*for (int i = 0; i < _size; i++){arr[i] = _arr[i];}*/_arr = new T[_capacity];}void Push(const T& x){Check_Capacity();_arr[_size]=x;_size++;}void Pop(){if (_size == 0)return;_size--;}size_t Size() const{return _size;}bool empty() const{_size = 0;}const T& top() const{return _arr[0];}protected:void Check_Capacity(){if (_size == _capacity){size_t newcapacity = _capacity * 2 + 1;T* tmp = new T[newcapacity];for (size_t i = 0; i < _capacity; i++){tmp[i] = _arr[i];}delete _arr;_arr = tmp;_capacity = newcapacity;}}private:T* _arr;size_t _size;size_t _capacity;};
队列

#include<iostream>using namespace std;template<typename T>struct QueueNode{    QueueNode<T>* _next;T _data;QueueNode():_next(NULL), _data(0){}};template<typename T>class Queue{public:Queue():_phead(NULL), _ptail(NULL){//_phead = (QueueNode<T>*)malloc(sizeof(QueueNode<T>));}void Push(const T& x){if (_phead == NULL){_phead = new QueueNode<T>;_phead->_data = x;_ptail = _phead;//_ptail = _ptail->_next;}else{_ptail->_next  =new QueueNode<T>;_ptail->_next-> _data = x;_ptail = _ptail->_next;}//size_t t = Size();}void Pop(){if (_phead == NULL){cout << "NULL"<<endl;}else{QueueNode<T>* tmp = new QueueNode<T>;tmp = _phead;_phead = _phead->_next;delete tmp;}size_t t = Size();}size_t Size() const{if (_phead == NULL){cout << "NULL" << endl;}int count = 0;QueueNode<T>* tmp = new QueueNode<T>;tmp = _phead;while (tmp != _ptail){tmp = tmp->_next;count++;}return count++;}const T& front() const{return _phead->_data;}const T& back() const{return _ptail->_data;}bool empty() const{if (_phead == NULL)return true;elsereturn false;}private:QueueNode<T>* _phead;QueueNode<T>* _ptail;};