首页 > 解决方案 > 用c中的堆栈检查字符串中的平衡括号

问题描述

我正在尝试编写一个程序,在其中我用数组实现堆栈并使用它们来检查给定的字符串是否具有平衡括号。

例如。如果输入 '(()){}[()]' ,程序会输出 'Balanced',否则如果输入 '({})[' 程序会输出 'Notbalanced'。

这部分是栈的数组实现。

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

#define MAX 50

int stack[MAX];
int top=-1;

void push(char val){
    if(top==MAX-1){
        printf("stack is already full,error\n");
    
    }else{
        top++;
        stack[top]=val;
    }
}

char pop(){
    if(top==-1){
        printf("not enough elements,error\n");
        exit(1);
    }else{
        top--;
        return stack[top];
    }
}

这部分是解决问题的常用方法的实现。

int isMatching(char c1, char c2){ 
    if(c1=='{' && c2=='}') 
        return 1; 
        
    else if(c1 =='(' && c2==')') 
        return 1; 
        
    else if(c1=='[' && c2==']') 
        return 1; 
    
    return 0; 
} 

int isBalanced(char str[]){
    int i=0;
    
    while(str[i]!='\0'){
        if(str[i]=='{' || str[i]=='[' || str[i]=='('){
            push(str[i]);
        }
        if(str[i]==')' || str[i] == ']' || str[i]=='}'){ 
            if(stack==NULL){
                return 0; 
            }
            if(!isMatching(pop(), str[i])){
                return 0;
            }
        } 
        i++; 

    }
    
    if(stack==NULL){
        return 1; // balanced parenthesis
    }else{
        return 0; // not balanced parenthesis
    }
}

这是用户输入字符串并测试它是否“平衡”的主要功能。

int main(){
    char str[MAX];
    int flag;
    printf("Enter the string with the brackets and etc.\n");
    fgets(str, sizeof(str),stdin); 
    flag=isBalanced(str);
    if(flag==1){
        printf("Balanced\n");
    }
    else{
        printf("Not balanced\n"); 
    }
    
    return 0;
}

例如,当我输入一个非常简单的示例时,我得到了错误的答案

Enter the string with the brackets and etc.
()
Not balanced

这应该输出“平衡”。我不明白这是怎么发生的。

标签: cstack

解决方案


if (stack==NULL)是这里的问题,堆栈永远不会为NULL。您需要通过验证来检查堆栈中是否仍有元素top > 0


推荐阅读