22栈的应用-中缀表达式转后缀表达式
Posted luanxin
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了22栈的应用-中缀表达式转后缀表达式相关的知识,希望对你有一定的参考价值。
main.c
#define _CRT_SECURE_NO_WARNING #include<stdio.h> #include<stdlib.h> #include<string.h> #include"Stack.h" //判断是不是数字 int IsNumber(char c) { return c >= ‘0‘ && c <= ‘9‘; } //判断是不是左括号 int IsLeft(char c) { return c == ‘(‘; } //判断是不是右括号 int IsRight(char c) { return c == ‘)‘; } //判断是不是运算符号 int IsOperate(char c) { return c == ‘+‘ || c == ‘-‘ || c == ‘*‘ || c == ‘/‘; } //返回运算符号优先级 int GetPriority(char c) { if (c == ‘*‘ || c == ‘/‘) { return 2; } if (c == ‘+‘ || c == ‘-‘) { return 1; } return 0; } typedef struct MYCHAR { StackNode node; char* p; }MyChar; //数字操作 void NumberOperate(char* p) { printf("%c", *p); } //创建MyChar MyChar* CreatMyChar(char* p) { MyChar* mychar = (MyChar*)malloc(sizeof(MyChar)); mychar->p = p; return mychar; } //左括号操作 void LeftOperate(LinkStack* stack,char* p) { Push(stack, (StackNode*)CreatMyChar(p)); } //右括号操作 void RightOperate(LinkStack* stack) { //先判断栈中有没有元素 while (StackLength(stack) > 0) { MyChar* mychar = (MyChar*)GetTop(stack); //如果匹配到左括号,弹出并输出 if (IsLeft(*(mychar->p))) { Pop(stack); break; } //输出 printf("%c", *(mychar->p)); //弹出 Pop(stack); //释放内存 free(mychar); } } //运算符号的操作 void OperateOperate(LinkStack* stack, char* p) { //先取出栈顶符号 MyChar* mychar = (MyChar*)GetTop(stack); if (mychar == NULL) { Push(stack, (StackNode*)CreatMyChar(p)); return; } //如果栈顶符号优先级低于当前字符的优先级 直接入栈 if (GetPriority(*(mychar->p)) < GetPriority(*p)) { Push(stack, (StackNode*)CreatMyChar(p)); return; } //如果栈顶符号优先级不低 else { while (StackLength(stack) > 0) { MyChar* mychar2 = (MyChar*)GetTop(stack); //如果优先级低 当前符号入栈 if (GetPriority(*(mychar2->p)) < GetPriority(*p)) { Push(stack, (StackNode*)CreatMyChar(p)); return; } //输出 printf("%c",*(mychar2->p)); //弹出 Pop(stack); //释放 free(mychar2); } } } int main() { char* str = "8+(3-1)*5";//831-5*+ char* p = str; //创建栈 LinkStack* stack = InitStack(); while (*p != ‘