zoukankan      html  css  js  c++  java
  • 数据结构之中缀表达式转为后缀


    #include<windows.h> #include<stdio.h> #define MaxSize 50 #define DataType char const int MAXSIZE = 100;//栈和队列的最大容量 typedef struct//栈结构体 { DataType elem[MAXSIZE]; int top; }SqStack; void InitStack(SqStack &s)//初始化栈 { s.top = 0; } bool Push(SqStack &s, DataType x)//向栈中加入一个数据元素 { if (s.top == MAXSIZE)//判满 return false; else { s.elem[s.top++] = x;//top永远在栈顶元素上一个 return true; } } bool Pop(SqStack &s, DataType &x)//从栈中输出一个数据元素(栈顶),并删除 { if (s.top != 0) { x = s.elem[--s.top]; return true; } else //判空 { printf("Underflow! "); return false; } } bool StackEmpty(SqStack s)//判断是否为空栈 { if (s.top == 0) return true; return false; } char GetTop(SqStack s)//获取栈顶元素,不删除 { return s.elem[s.top - 1]; } void shiftPostfix() { SqStack myStack; InitStack(myStack); char c=getchar(); char x; while(c!=' ') { if(c=='+'||c=='-') { while(!StackEmpty(myStack)&&GetTop(myStack)!='(')//栈中所有运算符优先级比加减号大,弹出 { Pop(myStack,x); printf("%c",x); } Push(myStack,c); printf(" ",c); //有运算符的地方加空格,来区分两个数 } else if(c=='*'||c=='/') { if(!StackEmpty(myStack)&&(GetTop(myStack)=='*'||GetTop(myStack)=='/'))//斩中只有乘除号优先级高,弹出 { Pop(myStack,x); printf("%c",x); Push(myStack,c); } else Push(myStack,c); printf(" ",c); } else if(c=='(') { Push(myStack,c); } else if(c==')') //右括号则将栈中左括号上面的全部弹出 { while(GetTop(myStack)!='(') { Pop(myStack,x); printf("%c",x); } Pop(myStack,x); } else //数字直接输出 printf("%c",c); c=getchar();//此步骤不要忽略,因为要进行下一次循环 } while (!StackEmpty(myStack)) { Pop(myStack,x); printf("%c",x); } printf(" "); } int main() { printf("请输入表达式: "); shiftPostfix(); system("pause"); return 0; } //example 8-(4-3)*3-12/4 //result 8 4 3- 3*- 12 4/-

     

  • 相关阅读:
    【转】【VS2008无法启动asp.net development server】的解决
    C#运用技巧(1)
    C# — WinForm 基本控件
    TB 需求分析
    C# 远程连接SQL 2005数据库
    SQL语句的运用
    如何跌倒
    国学堂-梁冬对话张长琳《人体的彩虹》系列
    帝范:中国最伟大帝王的沉思录
    web.xml 配置
  • 原文地址:https://www.cnblogs.com/BetterThanEver_Victor/p/5710049.html
Copyright © 2011-2022 走看看