堆栈的应用
一、 要求完成时间
实验开始后的第五周之前完成
二、 实验目的
掌握堆栈的使用。
三、 实验内容
- 输入一个数学表达式(假定表达式输入格式合法),计算表达式结果并输出。
- 数学表达式由单个数字和运算符“+”、“-”、“*”、“/”、“(、) ”构成,例如 2 + 3 * ( 4 + 5 ) - 6 / 4。
- 变量、输出采用整数,只舍不入。
四、注意事项
本题测试一定要多找几个测试用例,特别是复杂用例、边界用例。否则,很容易造成死机或者没有返回结果。
五、特别提醒:运行结果不稳定的原因
这个实验的程序容易出现运行结果不稳定情况,也容易出现死循环或者不正常退出的情况,
造成的原因大多是使用的非法内存,也就是数组变量越界引用,例如下面的引用就会造成非法引用。
int opStack[100];
Int I=0;
Int c;
…………如果你程序逻辑错误,运行到这个位置时c=101
opStack[c]=123; //这个时候opstack没有101数据,结果就操作了opstack数组后面的非法内存,
如果这个位置正好是程序,那就造成严重错误,如果是别的变量,比如是变量I的位置,那就造成i=123了,
这样的结果必然是错误的。
六、 测试用例及答案
测试如下用例,确保你的程序运行后出现完全一样的画面。
(操作系统提示“请按任意键继续。。。”等,可以不一样)。
#include<cstdio>
#include<iostream>
#include<cstring>
#include<string>
#include<stack>
#include<algorithm>
using namespace std;
string str;
int que[10000], len = 0;
int prior[300];
stack<char>sta;
int calus(int a, int b, char s)
{
return s == '+' ? a + b : s == '-' ? a - b : s == '*' ? a * b : a / b;
}
int main()
{
cout << "Input" << endl;
prior['+'] = 1;
prior['-'] = 1;
prior['*'] = 2;
prior['/'] = 2;
while (sta.size() > 0)sta.pop();
cin >> str;
str = "(" + str + ")";
for (int i = 0; i < str.length(); i++)
{
if (str[i] >= '0'&&str[i] <= '9')
{
int number = str[i] - '0';
while (str[i + 1] >= '0'&&str[i + 1] <= '9') number = number * 10 + str[++i] - '0';
que[len++] = number;
}
else
{
if (str[i] == '(') sta.push(str[i]);
else if (str[i] == ')')
{
while (sta.top() != '(')
{
len--;
que[len - 1] = calus(que[len - 1], que[len], sta.top());
sta.pop();
}
sta.pop();
}
else
{
while (!sta.empty() && sta.top() != '('&&prior[sta.top()] >= prior[str[i]])
{
len--;
que[len - 1] = calus(que[len - 1], que[len], sta.top());
sta.pop();
}
sta.push(str[i]);
}
}
}
cout << "Output"<<endl;
cout << que[--len] << endl;
cout << "End" << endl;
// }
return 0;
}