王道数据结构强化应用题打卡表2.1.7-2.1.9

#include"stdio.h" 
#include"string.h"
#define MAXSIZE 100

typedef struct Stack{
    char a[MAXSIZE];
    int top;
}SqlStack;

void initStack(SqlStack &s) {
    s.top = -1;
}

void push(SqlStack &s, char e) {
    s.a[++s.top] = e;
}

char pop(SqlStack &s) {
    char popE = s.a[s.top--];
    return popE;
}

char peek(SqlStack &s) {
    return s.a[s.top];
}

int main() 
{ 
    SqlStack s;
    initStack(s); 
    int matchSuccess = 1; 

    char expression[] = "[ ( 10 + 2 ) * 3 - [ 5 / ( 1 + 1 ) ] ]"; 
    int len = strlen(expression);

    for (int i = 0; i < len && matchSuccess; i++) {
        if (expression[i] == '[' || expression[i] == '(') {
            push(s, expression[i]); // 左括号入栈
        }
        else if (expression[i] == ']' || expression[i] == ')') {
            if (s.top == -1) { // 栈空,右括号多于左括号
                matchSuccess = 0;
                break;
            }
            
            char topChar = pop(s); 
            // 检查括号是否匹配
            if ((expression[i] == ']' && topChar != '[') || 
                (expression[i] == ')' && topChar != '(')) {
                matchSuccess = 0;
                break;
            }
        }
    }

    if (matchSuccess && s.top == -1) {
        printf("success: 括号匹配正确\n");
    } else {
        printf("wrong: 括号不匹配\n");
    }
    
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值