c++实现基本栈和队列

来源:互联网 发布:javassm开源项目源码 编辑:程序博客网 时间:2024/06/07 02:53

栈和队列是最基本的数据结构,自己实现栈和队列可以更好帮助自己理解和使用c++标准库中为我们提供的栈和队列的操作


//栈---通过链表实现template <class T>struct Node{T _value;Node<T>* _next;Node(){_next = NULL;}Node(T t){_value = t;_next = NULL;}};template <class T>class my_stack{typedef Node<T> Node;private:size_t cnts;//入栈数量Node* _head;public:my_stack(){cnts = 0;_head = new Node();}//入栈void Push(T t){Node *pnode = new Node(t);if(_head->_next==NULL){_head->_next = pnode;}else{pnode->_next = _head->_next;_head->_next = pnode;}cnts++;}//出栈T Pop(){if(_head->_next!=NULL){Node* tmp = _head->_next;_head->_next = _head->_next->_next;T a = tmp->_value;cnts--;delete tmp;return a;}}//返回栈顶元素T Top(){if(_head->_next!=NULL){return _head->_next->_value;}}//打印栈void Print_Stack(){if(_head->_next!=NULL){Node* tmp = _head;while(tmp->_next!=NULL){tmp = tmp->_next;cout<<tmp->_value<<" ";}}cout<<endl;}//获取栈内元素个数size_t Size(){return cnts;}//判空bool Empty(){if(cnts){return false;}return true;}};

//队列---通过顺序表实现#define DEFAULT_SZ 3template <class T>class my_queue{public:my_queue(){_array = (T*)malloc(sizeof(T)*(DEFAULT_SZ));_size = 0;_head = _array;_end = _array;_capacity = 3;}~my_queue(){free(_array);_array = NULL;_head = NULL;_end = NULL;}//在末尾加入一个元素void Push(T t){CheckCapacity();_array[_size] = t;_end = _array+_size;_size++;}void CheckCapacity(){T* tmp = _array;if(_size==_capacity){_array = (T*)realloc(_array,sizeof(T)*(_capacity+=DEFAULT_SZ));_capacity+=DEFAULT_SZ;if(_array == NULL){_array = tmp;}}}//删除第一个元素void Pop(){if(_head!=NULL){T* tmp = _head;_head ++;_size--;}}//返回第一个元素T Front(){if(_head!=NULL){return *_head;}}//返回最后一个元素T Back(){if(_end!=NULL){return *_end;}}//返回队列中元素的个数size_t Size(){return _size;}//如果队列空则返回真bool Empty(){if(_size){return false;}return true;}void Print_Queue(){T* tmp = _head;while(tmp!=_end){cout<<*tmp<<" ";tmp++;}cout<<*tmp<<" ";cout<<endl;}private:T* _array;size_t _size;size_t _capacity;T* _head;T* _end;};