逆波兰表达式(严7.38)

Description

一个四则运算算术表达式以有向无环图的邻接表方式存储,每个操作数原子都由单个字母表示。编写程序输出其逆波兰表达式。

Input

输入四则运算算术表达式。

Output

输出其逆波兰表达式。

  • Sample Input 
    (a+b)*c
  • Sample Output
    ab+c*

这个题要求是用有向无环图,老师说可以不用,我就没用~

前面写的那个逆波兰代码大概是有点问题,过不了这道题,所以改了一下……

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

typedef struct Stack{
    char data;
    struct Stack *next;
    struct Stack *top;
    struct Stack *bottom;
}Stack;

Stack *create()
{
    Stack *q=(Stack *)malloc(sizeof(Stack));
    q->bottom = (Stack*) malloc (sizeof(Stack));
    q->bottom->next = NULL;
    q->top = q->bottom;
    return q;
}

char getTop(Stack *s)
{
    return s->top->data;
}

void pop(Stack *s)
{
    Stack *q=s->top;
    s->top=s->top->next;
    free(q);
}

void push(Stack *s,char b){
    Stack *q=(Stack *)malloc(sizeof(Stack));
    q->data=b;
    q->next=s->top;
    s->top=q;
}

int judge(char a, char b){
    if((a == '*' && (b == '+' || b == '-')) || (a == '/' && (b == '+' || b == '-')))
        return 1;
    else
        return 0;
}

int main()
{
    char str[205];
    char ans[205];
    scanf("%s",&str);
    int i;
    Stack *s=create();
    int s1=strlen(str);
    for(i=0;i<s1;i++)
    {
        if(str[i]>='a'&&str[i]<='z')
        {
            printf("%c",str[i]);
        }
        else if(str[i]=='(')
        {
            push(s,str[i]);
        }
        else if(str[i]==')')
        {
            char top = getTop(s);
            while(top != '(')
            {
                printf("%c",top);
                pop(s);
                top = getTop(s);
            }
            pop(s);
        }
        else
        {
            while(1)
            {
                char top = getTop(s);
                if(judge(str[i], top) || s->top == s->bottom || top == '(')
                {
                    push(s, str[i]);
                    break;
                }
                else if(top == '+' || top == '-' || top == '*' || top == '/')
                {
                    printf("%c",top);
                    pop(s);
                }
                else
                {
                    break;
                }
            }
        }
    }
    while(s->top != s->bottom)
    {
        char top = getTop(s);
        printf("%c",top);
        pop(s);
    }
    printf("\n");
    return 0;
}

尝试了一下没有栈底指针,程序出了bug……栈底指针还是很好用的

  • 4
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值