【问题标题】:Why is the Stack not getting Emptied in this balanced parenthesis check C Program?为什么在这个平衡括号检查 C 程序中堆栈没有被清空?
【发布时间】:2021-07-08 13:21:28
【问题描述】:

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

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

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

【问题讨论】:

  • 还有一个问题。 if (C[i] == ']' &amp;&amp; Head-&gt;data != '[') 这里例如你应该立即断定弦不平衡。

标签: c data-structures linked-list stack


【解决方案1】:

你的推送应该只是

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-01-12
    • 1970-01-01
    • 2016-09-06
    • 2016-06-26
    • 2017-06-10
    • 2021-11-30
    • 2021-01-14
    • 2020-02-04
    相关资源
    最近更新 更多