int _tmain(int argc, _TCHAR* argv[])
{
stack sOperator, sOutput;
char szData[128];
sprintf(szData, "1+2+3*4+5*9-1");
for (int i = strlen(szData) - 1; i >= 0 ; i--)
{
switch(szData[i])
{
case '+' :
while ((!sOperator.empty()) && ((sOperator.top() == '*') || sOperator.top() == '/'))
{
sOutput.push(sOperator.top());
sOperator.pop();
}
sOperator.push(szData[i]);
break;
case '-' :
if (szData[i - 1] == '(')
{
sOutput.push(szData[i--]);
sOutput.push(szData[i--]);
}
else
{
while(!sOperator.empty() && (sOperator.top() == '*' || sOperator.top() == '/'))
{
sOutput.push(sOperator.top());
sOperator.pop();
}
sOperator.push(szData[i]);
}
break;
case '*' :
case '/' :
case ')' :
sOperator.push(szData[i]);
break;
case '(' :
while(sOperator.top() != ')')
{
sOutput.push(sOperator.top());
sOperator.pop();
}
sOperator.pop();
break;
default :
sOutput.push(szData[i]);
break;
}
}
while (!sOperator.empty())
{
sOutput.push(sOperator.top());
sOperator.pop();
}
while(!sOutput.empty())
{
printf("%c", sOutput.top());
sOutput.pop();
}
printf("\r\n");
system("pause");
return 0;
}
沒有留言:
張貼留言