//碰到数字直接输出
//运算符号:与栈顶符号进行优先级比较//若栈顶符号优先级比运算符号优先级低:此符号进栈(括号优先级最低)//若栈顶符号优先级不低于运算符号优先级:将栈顶符号一直弹出并输出,直到不满足条件之后进栈
//左括号:直接进栈
//右括号:将栈顶符号弹出并输出,直到匹配左括号
//最后将所有元素弹出并输出
#define _CRT_SECURE_NO_WARNINGS
#include"LinkList.c"
#include<stdio.h>
#include<stdlib.h>
#include<string.h>typedef struct MYCHAR {LinkNode node;char* p;
}MyChar;int IsNumber(char c)
{return c >= '0' && c <= '9';
}int IsLeft(char c)
{return c == '(';
}int IsRight(char c)
{return c == ')';
}//判断是不是运算符号
int IsOperator(char c)
{return c == '+' || c == '-' || c == '*' || c == '/';
}void NumberOpeartor(char* p)
{printf("%c", *p);
}//创建Mychar
MyChar* CreateMyChar(char *p)
{MyChar* mychar = (MyChar *)malloc(sizeof(MyChar));mychar->p = p;return mychar;
}//左括号的操作
void LeftOperator(LinkList* stack, char *p)
{Push_LinkList(stack, (LinkNode*)CreateMyChar(p));
}//右括号操作
void RightOperator(LinkList* stack)
{//先判断栈中有没有元素while (Size_LinkList(stack) > 0){MyChar* mychar = (MyChar*)Top_LinkList(stack);//如果匹配到左括号if (IsLeft(*(mychar->p))){Pop_LinkList(stack);break;}//输出printf("%c", *(mychar->p));//弹出Pop_LinkList(stack);//释放内存free(mychar);}
}//返回运算优先级
int GetPriority(char c)
{if (c == '*' || c == '/'){return 2;}if (c == '+' || c == '-'){return 1;}return 0;
}//运算符号的操作
void OperatorOperate(LinkList* stack, char *p)
{//先取出栈顶元素MyChar* mychar = (MyChar*)Top_LinkList(stack);if (mychar == NULL){Push_LinkList(stack, (LinkNode*)CreateMyChar(p));return;}//如果栈顶优先级低于当前字符优先级 直接入栈if (GetPriority(*(mychar->p)) < GetPriority(*p)){Push_LinkList(stack, (LinkNode*)CreateMyChar(p));return;}//如果栈顶符号优先级不低于当前字符优先级else {//while (Size_LinkList(stack) > 0)//{// MyChar* mychar2 = (MyChar*)Top_LinkList(stack);// //如果优先级低,当前符号入栈// if (GetPriority(*(mychar2->p)) < GetPriority(*p))// {// Push_LinkList(stack, (LinkNode*)CreateMyChar(p));// break;// }// printf("%c", *(mychar2->p));// //弹出// Pop_LinkList(stack);// //释放// free(mychar2); //}//将第一个获取的元素输出并弹出printf("%c", *(mychar->p));Pop_LinkList(stack);//一直比较直到满足条件while (Size_LinkList(stack) > 0){MyChar* mychar2 = (MyChar*)Top_LinkList(stack);//如果优先级低,当前符号入栈if (GetPriority(*(mychar2->p)) < GetPriority(*p)){Push_LinkList(stack, (LinkNode*)CreateMyChar(p));break;}printf("%c", *(mychar2->p));//弹出Pop_LinkList(stack);//释放free(mychar2); }//弹出完毕后最后将符号元素压入Push_LinkList(stack, (LinkNode*)CreateMyChar(p));}}
int main()
{char* str = "8+(3-1)*5+1-6";char* p = str;LinkList* stack = Init_linkList();while (*p != '\0'){//如果是数字,直接输出if (IsNumber(*p)){NumberOpeartor(p);}//如果是左括号,进栈if (IsLeft(*p)){LeftOperator(stack, p);}//如果是右括号,从栈顶弹出元素,直到匹配到左括号if (IsRight(*p)){RightOperator(stack); }//如果是运算符号if (IsOperator(*p)){OperatorOperate(stack, p);}p++;}while (Size_LinkList(stack) > 0){MyChar* mychar = (MyChar*)Top_LinkList(stack);printf("%c", *(mychar->p));Pop_LinkList(stack);free(mychar);}system("pause");return 0;
}