C++ 栈 (数组实现)
上一篇用链表实现了stack,这篇我们采用数组来存储数据,数组更容易理解,直接贴代码
第一、代码实现
1 #pragma once 2 #include <iostream> 3 using namespace std; 4 template <typename T> class StackArray { 5 public: 6 StackArray(int size) { 7 this->top = -1; 8 this->maxSize = size; 9 elements = new T[size]; 10 } 11 ~StackArray() { 12 delete [] elements; 13 } 14 bool push(T t); 15 T pop(); 16 bool isEmpty(); 17 void print(); 18 19 private: 20 int top = -1; 21 int maxSize; 22 T* elements; 23 24 }; 25 26 template<typename T> 27 bool StackArray<T>::push(T data) { 28 if (top==maxSize) 29 { 30 return false; 31 } 32 elements[++top] = data; 33 return true; 34 } 35 36 template<typename T> 37 T StackArray<T>::pop() { 38 if (top==-1) 39 { 40 exit(-1); 41 } 42 return elements[top--]; 43 } 44 45 template<typename T> 46 bool StackArray<T>::isEmpty() { 47 return top == -1; 48 } 49 50 template<typename T> 51 void StackArray<T>::print() { 52 int loop = top; 53 while (loop>=0) 54 { 55 cout << elements[loop] << endl; 56 loop--; 57 } 58 }
第二、测试运行
1 #include "pch.h" 2 #include "StackArray.h" 3 #include <iostream> 4 using namespace std; 5 6 int main() 7 { 8 StackArray<int> stack(10); 9 stack.push(1); 10 stack.push(3); 11 stack.push(10); 12 stack.push(40); 13 stack.pop(); 14 stack.push(30); 15 16 stack.print(); 17 18 std::cout << "Hello World!\n"; 19 }
个人签名:天行健,君子以自强不息