给出一个四则运算表达式,其中每个数字均为小于等于9且大于等于0。不考虑溢出,计算结果。表达式如"1+2*3-6+5-8/2+1+7"。
#include <iostream>
using namespace std;
struct Node
{
int value;
Node *next;
};
int calculate(char a[])
{
if (NULL == a)
{
return 0;
}
Node *head = new Node();
head->value = a[0] - '0';
Node *p = head;
char *q = (a + 1);
while ('\0' != *q)
{
Node *temp = new Node();
if (*q <= '9' && *q >= '0')
{
temp->value = *q - '0';
}
else
{
temp->value = *q;
}
p->next = temp;
p = p->next;
q++;
}
p->next = NULL;
// 计算乘除
p = head;
while (NULL != p)
{
if (p->next != NULL && (p->next->value == '*' || p->next->value == '/'))
{
if (p->next->value == '*')
{
p->value = (p->value) * (p->next->next->value);
}
else
{
p->value = (p->value) / (p->next->next->value);
}
Node *temp = p->next;
p->next = p->next->next->next;
delete temp->next;
delete temp;
}
else
{
p = p->next;
}
}
//计算加减
p = head;
while (NULL != p)
{
if (p->next != NULL && (p->next->value == '+' || p->next->value == '-'))
{
if (p->next->value == '+')
{
p->value = (p->value) + (p->next->next->value);
}
else
{
p->value = (p->value) - (p->next->next->value);
}
Node *temp = p->next;
p->next = p->next->next->next;
delete temp->next;
delete temp;
}
else
{
p = p->next;
}
}
int result = head->value;
delete head;
return result;
}