64,648
社区成员
发帖
与我相关
我的任务
分享
typedef int ElemType;
struct Stack{
ElemType *stack;
int top;
int MaxSize;
};
void InitStack(Stack& S)
{
S.MaxSize = 10;
S.stack = new ElemType[S.MaxSize];
if (!S.stack)
{
cerr<< "动态存储分配失败!"<< endl;
exit(1);
}
S.top = -1;
}
void Push(Stack& S, ElemType item)
{
if (S.top == S.MaxSize-1)
{
int k = sizeof(ElemType);
S.stack = (ElemType*)realloc(S.stack, 2*S.MaxSize*k);
S.MaxSize = 2*S.MaxSize;
}
S.top++;
S.stack[S.top] = item;
}
ElemType Pop(Stack& S)
{
if (S.top == -1)
{
cerr<< "Stack is empty!"<< endl;
exit(1);
}
S.top--;
return S.stack[S.top+1];
}
ElemType Peek(Stack& S)
{
if (S.top == -1)
{
cerr<< "Stack is empty!"<< endl;
exit(1);
}
return S.stack[S.top];
}
int Precedence(char op)
{
switch(op)
{
case '+':
case '-':
return 1;
case '*':
case '/':
return 2;
case '(':
case '@':
default:
return 0;
}
}
void Change(char* s1, char* s2)
{
Stack r;
InitStack(r);
Push(r, '@');
int i = 0, j = 0;
char ch = s1[i];
while (ch != '\0')
{
if (ch == ' ')
ch = s1[++i];
else if (ch == '(')
{
Push(r, ch);
ch = s1[++i];
}
else if (ch == ')')
{
while (Peek(r) != '(')
s2[j++] = Pop(r);
Pop(r);
ch = s1[++i];
}
else if (ch == '+' || ch == '-' || ch == '*' || ch == '/')
{
char w = Peek(r);
while (Precedence(w) >= Precedence(ch))
{
s2[j++] = w;
Pop(r);
w = Peek(r);
}
Push(r, ch);
ch = s1[++i];
}
else
{
if ((ch < '0' && ch > '9') && ch != '.')
{
cout<< "中缀表达式错误!"<<endl;
exit(1);
}
while ((ch >= '0' && ch <= '9') || ch == '.')
{
s2[j++] = ch;
ch = s1[++i];
}
s2[j++] = ' ';
}
}
ch = Pop(r);
while (ch != '@')
{
if (ch == '(')
{
cerr<< "expression error!"<< endl;
exit(1);
}
else
{
s2[j++] = ch;
ch = Pop(r);
}
}
s2[j++] = '\0';
}
int main()
{
char s1[300], s2[300];
memset(s1, '\0', sizeof(s1)); //memset函数的原型在头文件cstring里面 记得包含
memset(s2, '\0', sizeof(s2));
cout<< "请输入中序表达式:"<< endl;
cin>> s1;
Change(s1, s2);
cout<< "逆波特兰式是:"<< endl;
cout<< s2;
}