基本实现思想是通过栈来存储数据与运算符(包括加减乘除小括号)
代码如下
自己实现的一个栈
1 #include<iostream> 2 #include<stdlib.h> 3 4 using namespace std; 5 6 #define MAXSIZE 1024 7 8 template<class type> 9 class my_stack 10 { 11 int top; 12 type* my_s; 13 int maxsize; 14 15 public: 16 my_stack():top(-1),maxsize(MAXSIZE) 17 { 18 my_s = new type[maxsize]; 19 if(my_s==NULL) 20 { 21 cerr<<"动态存储分配失败"<<endl; 22 exit(0); 23 } 24 } 25 my_stack(int size):top(-1),maxsize(size) 26 { 27 my_s = new type[maxsize]; 28 if(my_s==NULL) 29 { 30 cerr<<"动态存储分配失败"<<endl; 31 exit(0); 32 } 33 } 34 ~my_stack() 35 { 36 delete[] my_s; 37 } 38 bool Empty(); 39 40 void Push(type tp); 41 42 type Top(); 43 44 void Pop(); 45 46 int Size(); 47 48 }; 49 50 template<class type> 51 bool my_stack<type>::Empty() 52 { 53 if(top == -1) 54 return true; 55 else 56 return false; 57 } 58 59 template<class type> 60 void my_stack<type>::Push(type tp) 61 { 62 if(top+1<maxsize) 63 { 64 top++; 65 my_s[top] = tp; 66 } 67 else 68 { 69 cout<<"栈满了"<<endl; 70 exit(1); 71 } 72 } 73 74 template<class type> 75 type my_stack<type>::Top() 76 { 77 if(top < 0) 78 { 79 cout<<"栈中没有元素"<<endl; 80 exit(1); 81 } 82 else 83 return my_s[top]; 84 } 85 86 template<class type> 87 void my_stack<type>::Pop() 88 { 89 if(top < 0) 90 { 91 cout<<"栈中没有元素"<<endl; 92 exit(1); 93 } 94 else 95 { 96 top--; 97 } 98 } 99 100 template<class type> 101 int my_stack<type>::Size() 102 { 103 if(top<0) 104 return 0; 105 else 106 return top+1; 107 }
主函数:
1 /** 2 *achive calcutor 3 * 4 *收到字符串表达式进行处理 5 * 6 */ 7 #include"mystack.h" 8 #include<string> 9 #define type1 float 10 11 my_stack<type1> num(100); 12 my_stack<char> sym(20); 13 14 15 bool isdigist(char c) 16 { 17 if(c>='0'&& c<='9'||c =='.') 18 return true; 19 else 20 return false; 21 } 22 23 int calcSize(char *calc) 24 { 25 int i = 0; 26 while(calc[i++]!='