您的位置:首页 > 其它

【栈】一个简答的四则运算计算器的实现

2015-03-22 22:34 573 查看
题目:输入一个中缀表达式的字符串,出去表达式的结果(只考虑整数)。

主要思路为先用栈把中缀表达式转换为后缀表达式,然后计算后缀表达式的值。

char * InfixToPostfix(char *s) {
if (s == NULL) return NULL;
stack<char> st;
stack<char> post;

char *p = s;
int priority[256] = {0}; //设置运算符优先级
priority['+'] = 0;
priority['-'] = 0;
priority['*'] = 1;
priority['/'] = 1;
priority['('] = -1;

while (*p != '\0') {
if (*p >= '0' && *p <= '9') {
post.push(*p++);
} else if (*p == '(') {
st.push(*p++);
} else if (*p == ')') {
while (!st.empty() && st.top() != '(') {
post.push(st.top());
st.pop();
}
st.pop(); //‘(’出栈
++p;
} else {
while (!st.empty() && priority[st.top()] >= priority[*p]) {
post.push(st.top());
st.pop();
}
st.push(*p++);
}
}

while (!st.empty()) {
post.push(st.top());
st.pop();
}

while (!post.empty()) {
st.push(post.top());
post.pop();
}

int len = strlen(s);
char *res = new char[len + 1];
int i = 0;
while (!st.empty()) {
res[i++] = st.top();
st.pop();
}
res[i] = '\0';

return res;
}

int BinaryComp(int a, int b, char c) {
switch (c) {
case '*':
return a * b;
break;
case '+':
return a + b;
break;
case '-':
return a - b;
break;
case '/':
return a /b;
break;
default:
break;
}
}

int CalCul(char *s) {
if (s == NULL)
return 0;
stack<int> st;
while (*s != '\0') {
if (*s >= '0' && *s <='9') {
st.push(*s - '0');
++s;
} else {
int a = st.top();
st.pop();
int b = st.top();
st.pop();
int res = BinaryComp(a, b, *s);
s++;
st.push(res);
}
}

return st.top();
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐