生成逆波兰表达式

 

 

#define MAXSIZE 10
typedef struct OpNode
{
    char data;
    struct OpNode *next;
}OpNode;

typedef struct OpStack
{
    OpNode *top;
}OpStack;

void op_pop(OpStack *s, char *d);
void op_push(OpStack *s, char data);
int op_len(OpStack *s);

int main()
{
    OpStack op = {NULL};
    char list[MAXSIZE] = {'0'};
    char el, d, e;
    printf("输入表达式,以=结束:");
    scanf("%c", &el);
    
    while(el != '=')
    {
        while(isdigit(el) || el == '.')
        {
            printf("%c", el);
            scanf("%c", &el);
        }
        printf(" ");
        switch(el)
        {
            case ')':
                if(op_len(&op)) {
                    do {
                        op_pop(&op, &e);
                        printf("%c", e);
                    }while(op_len(&op) && e != '(');
                }else {
                    printf("出错\n");
                    exit(-1);
                }
                break;
            case '+':
            case '-':
            case '(':
                if(op_len(&op))
                {
                    do {
                        op_pop(&op, &e);
                        if(e == '(')
                        {
                            op_push(&op, e);
                        }else {
                            printf("%c ", e);
                        }
                    }while(op_len(&op) && e != '(');
                }
                op_push(&op, el);
                break;
            case '*':
            case '/':
                op_push(&op, el);
                break;
            default:
                break;
        }
        
        if(el == '=')
        {
            break;
        }
        scanf("%c", &el); 
    }
    
    while(op_len(&op))
    {
        op_pop(&op, &e);
        printf("%c ", e);
    }
    return 0;
 } 
 

void op_push(OpStack *s, char data)
{
    OpNode *p = (OpNode *)malloc(sizeof(OpNode));
    p->data = data;
    p->next = s->top;
    s->top = p;
}

void op_pop(OpStack *s, char *d)
{
    OpNode *p = s->top;
    if(p == NULL)
    {
        return ;
    }
    *d = p->data;
    s->top = p->next;
    free(p);
    
}

int op_len(OpStack *s)
{
    int i = 0;
    OpNode *p = s->top;
    while(p != NULL)
    {
        p = p->next;
        i++;
    }
    
    return i;
}

 

转载于:https://www.cnblogs.com/buerr/p/7366865.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值