在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
1 没有使用模板的栈实现 1 #include <iostream> 2 #include <string> 3 using namespace std; 4 5 6 class Stack 7 { 8 public: 9 Stack(int size = 1024); 10 ~Stack(); 11 bool isEmpty(); 12 bool isFull(); 13 void push(int data); 14 int pop(); 15 private: 16 int* space; 17 int top; 18 19 }; 20 21 Stack::Stack(int size) 22 { 23 space = new int(size); 24 top = 0; 25 } 26 Stack::~Stack() 27 { 28 delete[]space; 29 } 30 bool Stack::isEmpty() 31 { 32 return top == 0; 33 } 34 bool Stack::isFull() 35 { 36 return top == 1024; 37 } 38 void Stack::push(int data) 39 { 40 space[top++] = data; 41 } 42 int Stack::pop() 43 { 44 return space[--top]; 45 } 46 47 int main() 48 { 49 Stack s(100); 50 int i = 0; 51 /*if (!s.isFull()) 52 { 53 s.push(10); 54 }*/ 55 while (!s.isFull()&&i<1024) 56 { 57 s.push(i); 58 i+=10; 59 } 60 i = 0; 61 while (!s.isEmpty()&&i<1024) 62 { 63 cout << s.pop() << endl; 64 i += 10; 65 } 66 cin.get(); 67 return 1; 68 } 2 使用模板以后的栈实现 1 #include <iostream> 2 #include <string> 3 using namespace std; 4 5 template<typename T> 6 class Stack 7 { 8 public: 9 Stack(int size) 10 { 11 space = new T[size]; 12 top = 0; 13 } 14 ~Stack(); 15 bool isEmpty(); 16 bool isFull(); 17 void push(T data); 18 T pop(); 19 private: 20 T* space; 21 int top; 22 23 }; 24 25 template<typename T> 26 Stack<T>::~Stack() 27 { 28 delete[]space; 29 } 30 template<typename T> 31 bool Stack<T>::isEmpty() 32 { 33 return top == 0; 34 } 35 template<typename T> 36 bool Stack<T>::isFull() 37 { 38 return top == 1024; 39 } 40 template<typename T> 41 void Stack<T>::push(T data) 42 { 43 space[top++] = data; 44 } 45 template<typename T> 46 T Stack<T>::pop() 47 { 48 return space[--top]; 49 } 50 51 int main() 52 { 53 Stack<double> s(100); 54 if (!s.isFull()) 55 s.push(10.4); 56 if (!s.isFull()) 57 s.push(10.5); 58 if (!s.isFull()) 59 s.push(10.6); 60 if (!s.isFull()) 61 s.push(10.7); 62 if (!s.isFull()) 63 s.push(10.8); 64 if (!s.isFull()) 65 s.push(10.9); 66 67 Stack<string> s1(100); 68 if (!s1.isFull()) 69 s1.push("ni"); 70 if (!s1.isFull()) 71 s1.push("hao"); 72 73 while (!s1.isEmpty()) 74 { 75 cout << s1.pop() << endl; 76 77 } 78 cin.get(); 79 return 1; 80 } 可以其他类型可以自己多敲敲哦 |
2023-10-27
2022-08-15
2022-08-17
2022-09-23
2022-08-13
请发表评论