微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

为什么在这个平衡括号检查 C 程序中堆栈没有被清空?

如何解决为什么在这个平衡括号检查 C 程序中堆栈没有被清空?

我正在尝试使用链表实现的堆栈来检查给定的括号数组是否平衡。我已经声明了一个全局结构指针。其余的代码是这样的。

struct node *Head;
struct node
    {
        char data;
        struct node *next;
    };
    
    struct node *getnewnode(char x)
    {
        struct node *temp = (struct node *)malloc(sizeof(struct node));
        temp->data = x;
        temp->next = NULL;
        return temp;
    }
    
    void push(char x)
    {
        printf("Pushing:%c\n",x);
        struct node *temp = getnewnode(x);
        if (Head == NULL)
            Head = temp;
        struct node *temp2 = Head;
        temp->next = temp2;
        Head = temp;
    }
    
    void pop()
    {
        struct node *temp = Head;
        if (temp == NULL)
            printf("nothing to POP");
        else
        {
            printf("POPing : %c\n",Head->data);
            Head = temp->next;
            free(temp);
        }
    }
    
    int main()
    {
        Head = NULL;
        char C[] = "{()}";
    
        for (int i = 0; i < strlen(C); i++)
        {
            if (C[i] == '{' || C[i] == '[' || C[i] == '(')
            {
                push(C[i]);
                printf("Push :%c\n",Head->data);
            }
            else if (C[i] == '}' || C[i] == ']' || C[i] == ')')
            {
                if (Head == NULL)
                {
                    printf("nothing in stack\n");
                }
                else if (C[i] == ']' && Head->data == '[')
                    pop();
    
                else if (C[i] == '}' && Head->data == '{')
                    pop();
    
                else if (C[i] == ')' && Head->data == '(')
                    pop();
    
                //else
                //  return 0;
            }
        }
    
        printf("Present Stack:%c\n",Head->data);
        if (Head->data == -1)
            printf("Balanced");
        else if (Head->data != -1)
        {
            printf("not Balanced");
        }
    }

我得到的输出是这个

 Pushing:{ 

 Push :{
  
 Pushing:(

 Push :(
  
 POPing : (

 POPing : {

 Present Stack:ÿ 

 not Balanced

如您所见,数组的所有元素都被弹出,但输出仍然不平衡。堆栈中仍然存在我不知道的值 'ÿ'。 有人可以指出这段代码有什么问题。我是不是遗漏了什么。

解决方法

你的推送应该是

void push(char x)
{
    printf("Pushing:%c\n",x);
    struct node* temp = getnewnode(x);
    temp.next = Head;
    Head = temp;
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。