一、利用数组实现一个简单的堆栈
1 #include <iostream> 2 3 const int MAXSIZE = 100; 4 5 class Stack{ 6 private: 7 int array[MAXSIZE]; 8 unsigned int index = 0; 9 public: 10 11 void push(int val); 12 int pop(); 13 int top(); 14 unsigned int length(); 15 void reset(); 16 }; 17 18 void Stack::push(int val){ 19 if(index < MAXSIZE){ 20 array[index++] = val; 21 } 22 } 23 int Stack::pop(){ 24 if(index > 0){ 25 return array[--index]; 26 } 27 } 28 int Stack::top(){ 29 if(index!=0) 30 return array[index-1]; 31 } 32 unsigned Stack::size(){ 33 return index; 34 } 35 void reset(){ 36 index = 0; 37 }
二、利用链表来实现堆栈基本操作
typedef struct node{ int value; node* next; }node, *pnode; class Stack{ private: pnode phead; unsigned int len = 0; public: Stack(){ phead = NULL; } void push(int val); int pop(); int top(); bool isEmpty(); unsigned int size(); void reset(); int operator[](const int index)const; }; void Stack::push(int val){ if(phead){ pnode temp = phead; phead = new node; phead->next = temp; phead->value = val; } else{ phead=new node; phead->value = val; phead->next = NULL; } len++; } int Stack::pop(){ int res = phead->value; pnode temp = phead; phead = phead->next; delete temp; len--; return res; } bool Stack::isEmpty(){ return len==0; }
//return the length of the stack unsigned int Stack::size(){ return len; } void Stack::reset(){ while(len>0){ pnode tmp = phead; phead=phead->next; delete tmp; len--; } }
//override the [] operator to access the stack like accessing an array int Stack::operator[](const int index)const{ if(index >= len) return NULL; else{ int i = len-1; pnode tmp = phead; while(i>index){ tmp=tmp->next; i--; } return tmp->value; } }