中缀表达式转后缀表达式
给定中缀表达式,用栈转为后缀表达式。
测试样例:
9+(3-2*1)*3+8/2
#include <iostream>
using namespace std;
#define InitSize 100
#define StackIncrement 50
typedef char ElemType;
typedef struct { //顺序栈定义
ElemType* elem; //栈数组
int top; //或ElemType*,栈顶指针
int size; //栈大小
} SeqStack;
int InitStack(SeqStack& S) { //初始化
S.elem = new ElemType[InitSize];
if (!S.elem) exit(1);
S.top = -1;
S.size = InitSize;
return 1;
}
int IsEmpty(const SeqStack& S) {
//判断栈是否空,空则返回1,否则返回0
return S.top == -1;
}
int IsFull(const SeqStack& S) {
//判断栈是否,满则返回1,否则返回0
return S.top == S.size;
}
int Push(SeqStack& S, ElemType& e) {
//若栈满返回0, 否则新元素 e 进栈并返回1
if (IsFull(S)) return 0;
S.top++; //先移动指针
S.elem[S.top] = e; //再加入新元素
return 1;
}
int Pop(SeqStack& S, ElemType& e) {
//若栈空返回0, 否则栈顶元素退出到e并返回1
if (IsEmpty(S)) return 0;
e = S.elem[S.top]; S.top--;
return 1;
}
int GetTop(const SeqStack& S, ElemType& e) {
//若栈空返回0, 否则栈顶元素读到e并返回1
if (IsEmpty(S)) return 0;
e = S.elem[S.top];
return 1;
}
void OverFlow(SeqStack& S) { //栈满处理
int newSize = S.size + StackIncrement;
ElemType* newS = new ElemType[newSize];
if (!newS) exit(1);
ElemType* src = S.elem,
* obj = newS;
for (int i = 0; i < S.size; i++)
*obj++ = *src++; //向新数组传送数据
delete[]S.elem; //释放老数组
S.elem = newS; //新数组作为栈数组
S.size = newSize; //新数组大小
} //栈顶指针不变
void Traverse(const SeqStack& S) {//遍历栈
if (IsEmpty(S)) cout << "空表,无法遍历" << endl;
for (int i = 0; i <= S.top; i++) {
cout << S.elem[i] << endl;
}
}
int Clear(SeqStack& S) {//清空栈
if (IsEmpty(S))return 1;
S.top = -1;
return 1;
}
int Destroy(SeqStack& S) {//销毁栈
free(S.elem);
S.elem = NULL;
S.size = 0;
S.top = NULL;
return 1;
}
int Priority(char θ1, char θ2) {
if (θ1 == θ2) return 1;
else {
if (θ2 == '*' || θ2 == '/') {
if (θ1 == '+' || θ1 == '-')return 0;
}
else {
return 1;
}
}
}
void InfixtoSuffix(SeqStack &S){
char p; char top; char out{};
while ((p = getchar()) != '\n') {
if (p == '+' || p == '-' || p == '*' || p == '/' || p == '(' || p == ')') {
if (IsEmpty(S)) {
Push(S, p);
}
else {
GetTop(S,top);
if (p == '('||top=='(')Push(S, p);
else if (p == ')') {
Pop(S, out);
while (out) {
cout << out;
Pop(S, out);
if (out == '(')break;
}
}
else {
GetTop(S, top);
if (Priority(top, p) == 0) {
Push(S, p);
}
else {
while (p) {
if (Priority(top, p) == 0 ||IsEmpty(S)) {
break;
}
Pop(S, out);
cout << out;
}
Push(S, p);
}
}
}
}
else {
int num = p - '0';
cout << num;
}
}
while (!IsEmpty(S)) {
char out1;
Pop(S, out1);
cout << out1;
}
}
int main() {
SeqStack S;
InitStack(S);//9+(3-2*1)*3+8/2
InfixtoSuffix(S);
cout<< InfixtoSuffix(S);
}