1// Head.h 2#include <iostream> 3using namespace std; 4 5#ifndef DEFAULT_STACK_SIZE 6#define DEFAULT_STACK_SIZE 1000 7#endif 8 9// end 10// iCoding@CodeLab 11// 12 13// Stack.h 14#include "Head.h" 15 16 17template <typename ElemType> 18class Stack 19{ 20 private: 21 ElemType *data; 22 int size; 23 int bottom; 24 int top; 25 public: 26 Stack (); 27 void push (ElemType elem); 28 ElemType pop (); 29 bool is_empty (); 30 bool is_full (); 31 int get_size (); 32 void expand_size (); 33}; 34 35 36// end 37// iCoding@CodeLab 38// 39 40#include "Stack.h" 41 42/////////////////////////////////////////////////////////// 43// Stack 44template <typename ElemType> 45Stack<ElemType>::Stack () 46{ 47 this->size = DEFAULT_STACK_SIZE; 48 this->data = new ElemType[this->size+1]; 49 this->bottom = 0; 50 this->top = 0; 51} 52 53/////////////////////////////////////////////////////////// 54// push 55template <typename ElemType> 56void Stack<ElemType>::push (ElemType elem) 57{ 58 if (is_full()) 59 { 60 expand_size (); 61 } 62 this->top++; 63 this->data[this->top] = elem; 64} 65/////////////////////////////////////////////////////////// 66// pop 67template <typename ElemType> 68ElemType Stack<ElemType>::pop () 69{ 70 ElemType elem_top; 71 elem_top = this->data[this->top]; 72 this->top--; 73 return elem_top; 74} 75/////////////////////////////////////////////////////////// 76// is empty 77template <typename ElemType> 78bool Stack<ElemType>::is_empty () 79{ 80 return (this->bottom >= this->top); 81} 82 83/////////////////////////////////////////////////////////// 84// is full 85template <typename ElemType> 86bool Stack<ElemType>::is_full () 87{ 88 return (this->size <= this->top); 89} 90 91/////////////////////////////////////////////////////////// 92// get size of Stack 93template <typename ElemType> 94int Stack<ElemType>::get_size () 95{ 96 return (this->top - this->bottom); 97} 98 99/////////////////////////////////////////////////////////// 100// expand_size 101template <typename ElemType> 102void Stack<ElemType>::expand_size () 103{ 104 ElemType* elem_data_tmp; 105 elem_data_tmp = new ElemType[this->size+1]; 106 for (int i = this->bottom + 1; i <= this->top; i++) 107 { 108 elem_data_tmp[i] = this->data[i]; 109 } 110 delete[] this->data; 111 this->size += DEFAULT_STACK_SIZE; 112 this->data = new ElemType[this->size+1]; 113 for (int i = this->bottom + 1; i <= this->top; i++) 114 { 115 this->data[i] = elem_data_tmp[i]; 116 } 117} 118 119// end 120// iCoding@CodeLab 121//
Stack类实现。模板
Easter79
2021-10-12
1123 0 0
点赞
收藏
评论区
加载中...