【问题标题】:Create pop() function stack implementation in C在 C 中创建 pop() 函数堆栈实现
【发布时间】:2021-03-18 16:16:07
【问题描述】:

我的程序根据用户输入创建一堆字符,以星号终止。 PopAll() 可以完美地逐个弹出每个元素,但反复使用 pop() 不会。我不明白这是怎么发生的,因为 popAll() 只是在后台使用 pop()。

谁能告诉我怎么回事?

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

struct NODE {
    char value;
    struct NODE *prev;
};

void push(char);
void pop();
void popAll();

int checkTerminator(char);

struct NODE *TOP = NULL;

int main()
{
    char input;
    
    while(checkTerminator(input) == 0){
        scanf("%c", &input);
        if(checkTerminator(input) == 0){
            push(input);
        }
    }
    
    printf("\nOutput:\n");

    // Doesn't pop three elements
    pop();
    pop();
    pop();

    // Succesfully pops all elements
    // popAll();

}

int checkTerminator(char value){
    switch(value){
        case '*':
            return 1;
        default:
            return 0;
    }
}

void push(char value){
    struct NODE *CURRENT = (struct NODE*) malloc(sizeof(struct NODE));

    CURRENT->value = value;
    CURRENT->prev = TOP;
    TOP = CURRENT;
}

void pop(){
    printf("%c", TOP->value);
    TOP = TOP->prev;
}

void popAll(){
    while(TOP != NULL){
        pop();
    }
}

【问题讨论】:

    标签: c char stack scanf singly-linked-list


    【解决方案1】:

    对于初学者来说,while 循环具有未定义的行为,因为变量 input 未初始化并且具有不确定的值。

    char input;
    
    while(checkTerminator(input) == 0){
    

    而且你必须在scanf的调用中使用以下格式

    scanf(" %c", &input);
          ^^^^
    

    否则您将读取空白字符,例如换行符'\n'

    函数pop 产生内存泄漏,因为它没有释放分配的节点。

    void pop(){
        printf("%c", TOP->value);
        TOP = TOP->prev;
    }
    

    函数checkTerminator可以写得更简单。例如

    int checkTerminator( char c )
    {
        return c == '*';
    }
    

    【讨论】:

      【解决方案2】:

      除了 Vlad 指出的问题之外,我还发现了以下问题:

      void pop(){
          printf("%c", TOP->value);
          TOP = TOP->prev;
      }
      

      您没有检查TOP 是否为NULL。最后,它变为 NULL,你最终访问 NULL ponter,这会给你分段错误。 (如果您只调用 pop() 多次)。

      【讨论】:

        猜你喜欢
        • 2016-10-24
        • 2013-12-21
        • 1970-01-01
        • 2011-05-04
        • 2010-12-15
        • 2020-02-14
        • 1970-01-01
        • 2010-11-27
        • 1970-01-01
        相关资源
        最近更新 更多