一.题意描述
题目要求解析一个含有数字,加号减号和括号的表达式,并算出其值,不能使用eval库函数。
#include <iostream> using namespace std; typedef struct { int* data; int to; }QStack;//在栈中-1,-2表示括号,-3,-4表示加减号 void Push(QStack* &q,int num) { q->data[q->to] = num; q->to++; } void init(QStack* &q) { q->to = 0; q->data = new int[600]; } int Pop(QStack* &q) { q->to--; return q->data[q->to]; } int Top(QStack* &q) { return q->data[q->to-1]; } class Solution { public: int calculate(string s) { int i; int temp; int temp2; int temp1; QStack *q = new QStack; init(q); Push(q,-1); for(i = 0;i <= s.length();i++) { if(i == s.length()) { temp2 = 0; while(1) { temp1 = Pop(q); temp = Pop(q); if(temp == -3) temp2 += temp1; else if(temp == -4) temp2 -= temp1; else { temp2+=temp1; Push(q,temp2); break; } } } else { if(s[i] == ‘ ‘ || s[i] == ‘"‘) continue; else if(s[i] == ‘(‘) Push(q,-1); else if(s[i] == ‘+‘) Push(q,-3); else if(s[i] == ‘-‘) Push(q,-4); else if(s[i] == ‘)‘) { temp2 = 0; while(1) { temp1 = Pop(q); temp = Pop(q); if(temp == -3) temp2 += temp1; else if(temp == -4) temp2 -= temp1; else { temp2+=temp1; Push(q,temp2); break; } } } else { if(Top(q) >= 0) { temp = Pop(q)*10 + s[i] - 48; Push(q,temp); } else Push(q,s[i]-48); } } } return Pop(q); } }; int main() { char temp[10000]; Solution calc; cin >> temp; string s(temp); cout << calc.calculate(s); }
内置stack版
#include <iostream> #include <stack>//在栈中-1,-2表示括号,-3,-4表示加减号 using namespace std; class Solution { public: int calculate(string s) { int i; int temp;//弹出的第二个数 int temp1;//弹出的第一个数 int temp2; stack<int> q; q.push(-1); for(i = 0;i <= s.length();i++) { //最后加一个右括号 if(i == s.length()) { temp2 = 0; while(1) { temp1 = q.top(); q.pop(); temp = q.top(); q.pop(); if(temp == -3) temp2 += temp1; else if(temp == -4) temp2 -= temp1; else { temp2+=temp1; q.push(temp2); break; } } } else { if(s[i] == ‘ ‘ || s[i] == ‘"‘) continue; else if(s[i] == ‘(‘) q.push(-1); else if(s[i] == ‘+‘) q.push(-3); else if(s[i] == ‘-‘) q.push(-4); else if(s[i] == ‘)‘) { temp2 = 0; while(1) { temp1 = q.top(); q.pop(); temp = q.top(); q.pop(); if(temp == -3) temp2 += temp1; else if(temp == -4) temp2 -= temp1; else { temp2+=temp1; q.push(temp2); break; } } } else//输入的是数字 { if(q.top() >= 0) { temp = q.top()*10 + s[i] - 48; q.pop(); q.push(temp); } else q.push(s[i]-48); } } } return q.top(); } }; int main() { char temp[10000]; Solution calc; cin >> temp; string s(temp); cout << calc.calculate(s); }
原文:http://www.cnblogs.com/yukeyi14/p/4899664.html