简体   繁体   English

在 c 中使用堆栈检查表达式的平衡括号

[英]checking balance parenthesis of an expression using stack in c

Application of stack堆栈的应用

So recently came across this question where an expression is given with some parenthesis and we are told to check whether the expression is balanced or not.所以最近遇到了这个问题,其中一个表达式带有一些括号,我们被告知检查表达式是否平衡。

This is what i have done till now, but i cant seem to pop the elements from the stack.这是我到目前为止所做的,但我似乎无法从堆栈中弹出元素。 When i pop it in the else part of the function i can seem to properly compare it.当我将它放在 function 的其他部分时,我似乎可以正确比较它。

How can i make my code work, and what is the reason for the simple comparison condition not to work?我怎样才能使我的代码工作,简单比较条件不起作用的原因是什么?

#include <stdio.h>
#include <stdbool.h>

char stack[30];
int top = 0;

bool spec = 0;
void push(char x){
    if (top == 30)
        printf("Full\n");
    else{
        stack[top] = x;
        top++;
    }
}

void pop(char x){
    if (top == 0)
        spec = 1;
    else{
        if (x == stack[top-1])
            top--;
    }
}

int main()
{
    char temp[30];
    scanf("%s", temp);

    for (int i = 0; temp[i] != '\0'; i++)
    {
        if (temp[i] == '(' || temp[i] == '{' || temp[i] == '[')
            push(temp[i]);
        else if (temp[i] == ')' || temp[i] == '}' || temp[i] == ']')
            pop(temp[i]);
    }

    for (int i = 0; i < top; i++){
        printf("%c", stack[i]);
    }
    if (top != 0)
        printf("Unbalanced");
    else
        printf("Balanced");
    return 0;
}

When you read the closing parenthesis or braces you should not only pop the stack, but also compare the popped value to see if it's a corresponding opening parenthesis or brace.当您阅读右括号或大括号时,您不仅应该弹出堆栈,还应该比较弹出的值以查看它是否是相应的左括号或大括号。

So you first need to modify the pop function to return the popped value:所以首先需要修改pop function返回pop出的值:

char pop(void)
{
    if (top > 0)
    {
        return stack[--top];
    }
    else
    {
        return 0;  // Error: Stack underflow
    }
}

Then you need to get the popped character and check it:然后你需要得到弹出的字符并检查它:

if (temp[i] == '(' || temp[i] == '{' || temp[i] == '[')
{
    push(temp[i]);
}
else if (temp[i] == ')' || temp[i] == '}' || temp[i] == ']')
{
    char opening = pop();  // Pop and get value

    if ((temp[i] == ')' && opening != '(') ||
        (temp[i] == '}' && opening != '{') ||
        (temp[i] == ']' && opening != '['))
    {
        // TODO: Not matching, handle it in some appropriate way
    }
}

Once one gets going, it's hard to stop with these things.一旦一个人开始,就很难停止这些事情。 Intending to "lightly touch" your code, this is what resulted.打算“轻轻触摸”您的代码,这就是结果。 I hope the comments make clear what it is doing... Primarily, for any of the 3 types of "open", this "pushes" its mate onto the stack.我希望评论能清楚地说明它在做什么......首先,对于 3 种“打开”类型中的任何一种,这会将其伴侣“推”到堆栈上。 Then when a "close" is encountered, it is passed to popExpect() for validation against what's on the top of the stack (if anything).然后,当遇到“关闭”时,它被传递给popExpect()以验证堆栈顶部的内容(如果有的话)。 That function returns a boolean yes/no to continue. function 返回 boolean 是/否以继续。

Anyway...反正...

#include <stdio.h>

#define STACKSIZE 30 // One "magic number" in this source

char stack[ STACKSIZE ]; // Global, but let's go with it
int top = 0;

void push( char x ) { // little change here
    if( top == STACKSIZE )
        puts( "Stack Full");
    else
        stack[ top++ ] = x;
}

bool popExpect( char c ) { // compare expected char on top with passed char
    return top && c == stack[ --top ];
}

// function "broken out" for repeated tests
bool chk( const char *str ) {
    char *cp, pairs[] = "(){}[]"; // three important pairs

    bool isGood = true; // optimism

    // while good and not finished string
    for( int i = 0; isGood && str[ i ]; i++ )

        // is this char one of the "special" ones?
        if( ( cp = strchr( pairs, str[ i ] ) ) != NULL ) {

            // which "special" char is it?
            int off = cp - pairs;

            // because "paired" 0,2,4 are open, 1,3,5 are close
            if( off%2 == 0 ) // opening
                push( cp[1] ); // push the close that matches this open
            else // special closing
                isGood = popExpect( str[ i ] ); // does this close match?
        }

    // all good and nothing left on the stack
    return isGood && top == 0;
}

int main() {
    const char *s1 = "(foobar)({}){bar}[[[(foo)]]]"; // balanced
    const char *s2 = "(foobar)({}){ { bar}[[[(foo)]]]"; // unbalanced open
    const char *s3 = "(foobar)({}){ ] bar}[[[(foo)]]]"; // unbalanced close

    puts( chk( s1 ) ? "Balanced" : "Unbalanced" );
    puts( chk( s2 ) ? "Balanced" : "Unbalanced" );
    puts( chk( s3 ) ? "Balanced" : "Unbalanced" );

    return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM