簡體   English   中英

這是一個使用堆棧檢查C中括號平衡的程序,但未按預期工作

[英]It's a program for checking balance of parenthesis in C using a stack but it is not working as expected

這是一個使用堆棧檢查C中括號平衡的程序,但未按預期工作。

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

struct node {
    char data;
    struct node *next;
};
struct node *top = NULL;   //top stores address of top element of stack  

void push(char data) {   //inserting element
    struct node *temp = (node *)malloc(sizeof(struct node));
    temp->data = data;
    temp->next = NULL;
    if (top == NULL) {
        top = temp;
        return;
    }
    temp->next = top;
    top = temp;
}

void pop() {  //removing element
    struct node *temp = top;
    if (top == NULL) {
        printf("No element to delete");
        return;
    }
    top = top->next;
    free(temp);
}

char Top() { //fn tht return top element of stack
    return top->data;
}

int isEmpty() {
    if (top != NULL) {
        return 1;
    } else
        return 0;
}

int ArePair(char opening, char closing) {
    if (opening == '(' && closing == ')')
        return 1;
    else if (opening == '{' && closing == '}')
        return 1;
    else if (opening == '[' && closing == ']')
        return 1;
    return 0;
}

int Arebalanced(char exp[]) {
    int i;
    for (i = 0; i < strlen(exp); i++) {
        if (exp[i] == '(' || exp[i] == '{' || exp[i] == '[')
            push(exp[i]);
        else if (exp[i] == ')' || exp[i] == '}' || exp[i] == ']') {
            if (isEmpty() || !ArePair(Top(), exp[i]))
                return 0;
            else
                pop();
        }
    }
    return isEmpty() ? 1 : 0;
}

int main() {  
    int i;
    char a[50];
    printf("Enter expession: ");
    gets(a);
    if (Arebalanced(a)) {
        printf("balanced \n");
    } else
        printf("not balanced\n");
}

函數isEmpty()似乎不正確:如果堆棧不為空,則返回1

試試這個版本:

int isEmpty() { return top == NULL; }

並且不要使用 gets()

int main(void) {
    char a[50];
    printf("Enter expression: ");
    if (fgets(a, sizeof a, stdin)) {
        if (Arebalanced(a)) {
            printf("balanced \n");
        } else {
            printf("not balanced\n");
        }
    }
    return 0;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM