七、实验目的
掌握堆栈的使用。
八、实验内容
7、输入一个数学表达式(假定表达式输入格式合法),计算表达式结果并输出。
8、数学表达式由单个数字和运算符“+”、“-”、“*”、“/”、“(、) ”构成,例如 2 + 3 * ( 4 + 5 ) - 6 / 4。
9、变量、输出采用整数,只舍不入。
九、注意事项
本题测试一定要多找几个测试用例,特别是复杂用例、边界用例。否则,很容易造成死机或者没有返回结果。
十、特别提醒:运行结果不稳定的原因
这个实验的程序容易出现运行结果不稳定情况,也容易出现死循环或者不正常退出的情况,造成的原因大多是使用的非法内存,也就是数组变量越界引用,例如下面的引用就会造成非法引用。
int opStack[100];
Int I=0;
Int c;
…………如果你程序逻辑错误,运行到这个位置时c=101
opStack[c]=123; //这个时候opstack没有101数据,结果就操作了opstack数组后面的非法内存,如果这个位置正好是程序,那就造成严重错误,如果是别的变量,比如是变量I的位置,那就造成i=123了,这样的结果必然是错误的。
#include<iostream>
#include<Exception>
#include<string>
using namespace std;
template<class T>
class Node {
public:
T data;
Node<T>* link;
};
class OutOfBounds {
public:
OutOfBounds() {
cout << "Out Of Bounds!" << endl;
}
};
template<class T>
class Chain {
public:
Chain() { top = 0; }
~Chain();
T Top()const;
Chain<T>& Add(const T& x);
Chain<T>& Delete(T& x);
Node<T>* top;
};
template<class T>
Chain<T>::~Chain() {
Node<T>* next;
while (top) {
next = top->link;
delete top;
top = next;
}
}
template<class T>
T Chain<T>::Top()const {
if (top == 0) {
cout << "栈为空!!!" << endl;
throw OutOfBounds();
}
else {
return top->data;
}
}
template<class T>
Chain<T>& Chain<T>::Add(const T& x) {
Node<T> * p = new Node<T>;
p->data = x;
p->link = top;
top = p;
return *this;
}
template<class T>
Chain<T>& Chain<T>::Delete(T& x) {
if (top == 0) {
throw OutOfBounds();
}
x = top->data;
Node<T>* p = top;
top = p->link;
delete p;
return *this;
}
int Suan(int a, int b, char s) {
int c;
switch (s) {
case '+':
c = a + b;
break;
case '-':
c = b - a;
break;
case '*':
c = a * b;
break;
case '/':
c =(int)( b / a);
break;
default:
break;
}
return c;
}
int main000() {
cout << "Input" << endl;
Chain<char> fuhao;
Chain<int>shu;
string str="";
string ss = "";
string da = "";
cin >> str;
str += "#$";
int i = 0;
while (str[i] != '#$') {
if (str[i] >= '0' && str[i] <= '9') {
int num = str[i] - '0';
while (str[i + 1] >= '0' && str[i + 1] <= '9') {
num = num * 10 + (str[++i] - '0');
}
shu.Add(num);
}
else {
if (str[i] == '(') {
fuhao.Add(str[i]);
i++;
}
else if (str[i] == ')') {
while (fuhao.Top() != '(') {
char x;
int m, n;
fuhao.Delete(x);
shu.Delete(n);
shu.Delete(m);
int result=Suan(m, n, x);
shu.Add(result);
}
i++;
}
else if (str[i] == '+' || str[i] == '-' || str[i] == '*' || str[i] == '/') {
char x;
int m, n;
fuhao.Delete(x);
shu.Delete(n);
shu.Delete(m);
int result = Suan(m, n, x);
shu.Add(result);
i++;
}
}
}
cout <<" Output" << endl;
cout << shu.Top()<<endl;
cout << "End" << endl;
return 0;
}