暑假集训7.29 一般表达式转换后缀表达式(手写模拟栈....)sdutoj2132

数据结构实验之栈二:一般算术表达式转换成后缀式

Time Limit: 1000MS Memory limit: 65536K

题目描述

对于一个基于二元运算符的算术表达式,转换为对应的后缀式,并输出之。

输入

输入一个算术表达式,以‘#’字符作为结束标志。

输出

输出该表达式转换所得到的后缀式。

示例输入

a*b+(c-d/e)*f#

示例输出

ab*cde/-f*+

///思路

///1.如果是数字符 直接打印 (也可以保存到字符数组)因为中缀转换不改变数字符位置 i++


///2.如果栈空 运算符或括号压栈 i++


///3.栈不空 栈外元素与栈顶比较 for(;;)

///i.左括号直接压栈

/// ii.栈外元素优先级高于栈顶  将其压栈(如果栈顶是括号 也执行此步骤)

///iii.栈外元素优先级低于等于栈顶 栈顶元素出栈打印  栈外元素压栈 while():一直到3-ii.成立 即栈外元素压栈....

///iiii.栈外元素是右括号 将栈内元素依次出栈打印  直到左括号 舍弃括号 不输出

///Accode

#include <iostream>
#include <cstdio>
using namespace std;
const int maxn=100010;
typedef struct Stack
{
    char *top,*base;
    int Size;
};

void Creat(Stack &s) ///建栈
{
    s.base=new char[maxn];
    s.top=s.base;
}

void push(Stack &s,char ch) ///压ch入栈
{
    s.top++;
    *s.top=ch;
}

bool Empty(Stack &s)  ///是否为空
{
    if(s.base==s.top)
    {
        return 1;
    }
    return 0;
}

void pop(Stack &s) ///出栈
{
    if (!Empty(s))
    {
        s.top--;
    }
}

void print(Stack &s) ///打印
{
    while(!Empty(s))
    {
        cout<<*s.top;
        pop(s);
    }
    cout<<endl;
}

int change(Stack &s,char st[],int n)  ///转化为后缀
{
    int  i;
    for (i=1; i<=n; i++)
    {
        if (st[i]>='a'&&st[i]<='z')
        {
            cout<<st[i];
        }
        else
        {
            if (Empty(s))
            {
                push(s,st[i]);
            }

            else if (st[i]=='+'||st[i]=='-')/// step 3—iii
            {
                while (*s.top=='*'||*s.top=='/'||*s.top=='+'||*s.top=='-')
                {
                    cout<<*s.top;
                    s.top--;
                }
                push(s,st[i]);/// step 3-ii
            }
            else if(st[i]=='*'||st[i]=='/')/// step 3-iii
            {
                while(*s.top=='*'||*s.top=='/')
                {
                    cout<<*s.top;
                    s.top--;
                }
                push(s,st[i]);/// step 3-ii
            }
            else if (st[i]==')')
            {
                while(*s.top!='(')
                {
                    cout<<*s.top;
                    pop(s);
                }
                pop(s);///舍弃左括号
            }
            else if (st[i]=='(')
            {
                push(s,st[i]);
            }
        }
    }
}
int main()
{
    char ch,st[maxn];
    int i=0;
    Stack s;
    Creat(s);
    while(ch=getchar())
    {
        if(ch!='#')///读取#结束
        {
            i++;
            st[i]=ch;
        }
        else if(ch=='#')
        {
            break;
        }
    }
    change(s,st,i);  /// 表示字符串下标1--i
    print(s);
    return 0;
}


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值