利用栈实现中缀表达式转化为后缀表达式

#include "stdio.h"
#include "stdlib.h"
#include "stdbool.h"
#include "string.h"


typedef struct {
    char data[100];
    int top;                // 栈顶指针
}SqStack;


void convert(char* arr, int strlen, char* res);

int main() {
    char arr[100];
    char res[100];

    scanf("%s", arr);
    convert(arr, strlen(arr), res);
    printf("%s", res);

    return 0;
}

void convert(char* arr, int strlen, char* res) {
    // 创建栈
    SqStack sqStack = {{}, -1};

    int index = 0;
    for (int i = 0; i < strlen; ++i) {
        // 若是数字直接加入res数组
        if ('0' <= arr[i] && '9' >= arr[i]) {
            // 注意数字可能有多位
            while ('0' <= arr[i] && '9' >= arr[i]) {
                //printf("%c\n", arr[i]);
                res[index++] = arr[i++];
            }
            i--;
        } else if (arr[i] != ')') {
            // 运算符入栈
            sqStack.data[++sqStack.top] = arr[i];
        } else {
            // 碰见右括号栈内运符出栈
            while (sqStack.data[sqStack.top] != '(') {
                //printf("%c\n", sqStack.data[sqStack.top]);
                res[index++] = sqStack.data[sqStack.top--];
            }
            sqStack.top--;
        }
    }
    
    // 栈中若有剩余则全部出栈
    while (sqStack.top > -1) {
        res[index++] = sqStack.data[sqStack.top--];
    }
    res[index] = '\0';
}
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值