zoukankan      html  css  js  c++  java
  • 中缀表达式转后缀表达式

    转换要按照运算符优先级。

    (s) 为中缀表达式,(sta) 为转换中维护的一个栈,(a) 为最终的后缀表达式。

    顺序扫描一遍中缀表达式。如果遇到数,直接加入到后缀表达式中;如遇到操作符:

    1. 栈为空,直接将该操作符入栈。

    2. 否则,一直弹栈,直到栈顶操作符优先级更低(更低指严格更低,优先级相同的也要弹栈)

    从栈内弹出的元素直接加入到后缀表达式中。
    最后扫描完后需要把栈内的元素弹出。

    for(int i=1;i<=n;i++){
        if('0'<=s[i]&&s[i]<='9')
            a[++m]=s[i];
        if(s[i]=='^') sta[++top]=s[i];
        if(s[i]=='*'||s[i]=='/'){
            while(sta[top]=='^'||sta[top]=='*'||sta[top]=='/')
                a[++m]=sta[top--];
            sta[++top]=s[i];
        }
        if(s[i]=='+'||s[i]=='-'){
            while(sta[top]=='^'||sta[top]=='*'||sta[top]=='/'||sta[top]=='+'||sta[top]=='-')
                a[++m]=sta[top--];
            sta[++top]=s[i];
        }
        if(s[i]=='(') sta[++top]='(';
        if(s[i]==')'){
            while(sta[top]!='(')
                a[++m]=sta[top--];
            top--;
        }
    }
    while(top) a[++m]=sta[top--];
    for(int i=1;i<=m;i++) printf("%c ",a[i]);
    
  • 相关阅读:
    Objective-C实用类和协议
    KVC(Key-Value-Coding)和KVO(Key-Value-Observer)
    Xcode
    IOS模拟器
    沙盒机制
    UIScrollView
    NSPredicate
    输入控件适应键盘
    10步成为专业iOS开发者——新手向,从零起步
    2015 年五大移动端设计趋势
  • 原文地址:https://www.cnblogs.com/wwlwQWQ/p/14015552.html
Copyright © 2011-2022 走看看