C程序检查圆括号

时间:2018-08-05 19:46:31

标签: c arrays data-structures stack

这是我的程序,用于检查括号的平衡。它没有显示任何错误,也没有警告,但没有显示应显示的确切输出。

注意,我有点不确定我的checkBalanced函数是否有错误

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

struct Stack
{
    int top;
    int capacity;
    int *array;
};

struct Stack *createstack(int capacity)
{
    struct Stack *stack = (struct Stack *)malloc(sizeof(struct Stack));
    if (!stack)
        return NULL;
    stack->top = -1;
    stack->capacity = capacity;

    stack->array = (int *)malloc(sizeof(int) * stack->capacity);
    if (!stack->array)
        return NULL;
    return stack;
}

// to check whether the stack is empty

int isempty(struct Stack *stack)
{
    return stack->array[stack->top--];
}

char pop(struct Stack *stack)
{
    return stack->array[stack->top--];
}

void push(struct Stack *stack, char exp)
{
    stack->array[++stack->top] = exp;
}

// returns the peak value of stack

char peek(struct Stack *stack)
{
    return stack->array[stack->top];
}

// function to check the correct matching of paranthesis at stack top and exp[i]

int ismatchingpair(char char1, char char2)
{
    if (char1 == '(' && char2 == ')')
        return 1;
    if (char1 == '[' && char2 == ']')
        return 1;
    if (char1 == '{' && char2 == '}')
        return 1;
    return 0;
}

// function to check balancing of paranthesis

int checkBalanced(char *exp)
{
    struct Stack *stack = createstack(strlen(exp));
    if (!stack)
        return NULL;

    for (int i = 0; exp[i]; ++i)
    {
        if (exp[i] == '(' || exp[i] == '{' || exp[i] == '[')
            push(stack, exp[i]);
        else if (exp[i] == ')' || exp[i] == '}' || exp[i] == ']')
        {
            if (isempty(stack) || !ismatchingpair(peek(stack), exp[i]))
                return -1;
            else
                pop(stack);
        }
    }
    printf("parenthesis are balanced");
}

// main function

int main()
{
    char exp[50] = "(){}";

    checkBalanced(exp);
    return 0;
}

1 个答案:

答案 0 :(得分:2)

我认为问题出在您的corr = np.zeros((48,80)) 函数上。您的isempty()返回一些值,这对您的isempty()if-condition无效。 if条件函数应if (isempty(stack) || !ismatchingpair(peek(stack), exp[i]))return 0

修改为:-

1

输出:-

int isempty(struct Stack *stack)
{
    if (stack->top == -1)
        return 1;

    return 0;
} 

还要确保parenthesis are balanced 返回int checkBalanced(char *exp)值。 NULL 不是整数,而是指针。

建议将其修改为:-

int