数据结构的作业不难但是debug 了很久啊啊啊好气就随便记一下。
输入格式:每个数字与运算符之间以空格分隔 如
10 * 20 + ( 30 - 40 / 2 ) * 5
#include <iostream>
#include <string>
#include <sstream>
#include <cstdlib>
using namespace std;
template <class ElemType>
class Stack{
private:
int num,max_elem;
ElemType *top,*bottom;
public:
Stack(int x) {
num=0;
max_elem=x;
bottom = new ElemType[x];
top = bottom;
}
void push(ElemType e) {
num++;
if (num>max_elem) {
num--;
} else {
*top = e;
top++;
}
}
ElemType* pop() {
if (num>0) {
num--;
top--;
return top;
} else return NULL;
}
ElemType* getTop() {return top; }
int getLength() { return num; }
~Stack() {
delete []bottom;
}
bool isEmpty() {
return (top==bottom);
}
};
int compare(char c1,char c2) {
if (c1=='+'||c1=='-') {
if (c2=='+'||c2=='-'||c2=='/'||c2=='*') return -1; else return 1;
} else
if (c1=='*'||c1=='/') {
if (c2=='+'||c2=='-'||c2=='(') return 1; else return -1;
} else
if (c1=='(') return 1;
else if (c1==')') {
if (c2=='(') return 0; else return -1;
}
}
void manage(Stack<int> &s1,Stack<char> &s2,char c) {
char tc = *(s2.getTop()-1);
if (tc=='#') s2.push(c); else {
int t = compare(c,tc);
if (t>0) s2.push(c); else
if (t==0) {
s2.pop();
return;
} else {
int n1 = *(s1.pop());
int n2 = *(s1.pop());
s2.pop();
if (tc=='+') {
s1.push(n1+n2);
} else
if (tc=='-') {
s1.push(n2-n1);
} else
if (tc=='*') {
s1.push(n1*n2);
} else
if (tc=='/') {
s1.push(n2/n1);
}
manage(s1,s2,c);
}
}
}
void calculate(Stack<int> &s1,Stack<char> &s2) {
char c = *(s2.pop());
while (c!='#') {
int n1 = *(s1.pop());
int n2 = *(s1.pop());
if (c=='+') {
s1.push(n1+n2);
} else
if (c=='-') {
s1.push(n2-n1);
} else
if (c=='*') {
s1.push(n1*n2);
} else
if (c=='/') {
s1.push(n2/n1);
}
c = *(s2.pop());
}
}
int main() {
string s;
getline(cin,s);
string st[100];
istringstream is(s);
int i=0;
while (is>>st[i]) {
i++;
}
int length= i+1;
st[length-1] = "#";
Stack<int> s1(100);
Stack<char> s2(100);
s2.push('#');
i=0;
while (i<length) {
if (st[i].length()>1) s1.push(atoi(st[i].c_str())); else
if (st[i][0]<'0'||st[i][0]>'9') {
char c = st[i][0];
if (c!='#') {
char tc = *(s2.getTop()-1);
if (tc=='#') s2.push(c); else manage(s1,s2,c);
} else calculate(s1,s2);
} else s1.push(atoi(st[i].c_str()));
i++;
}
cout<<*(s1.pop());
}