【问题标题】:After deleting Linked List it is still printing删除链接列表后,它仍在打印
【发布时间】:2017-10-01 10:03:39
【问题描述】:

我在练习链表: 即使在使用deleteList() 函数删除列表后,我的printList() 函数仍在打印整个列表,这是我的代码,我的代码有什么问题?是删除函数声明还是函数调用有问题,我的main()printList()函数有什么错误吗?

我在互联网上搜索并尝试了教程网站上的代码。

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

typedef struct node {
    int data;
    struct node *next;
} node;

void deleteList(node **head);   
void printList(node *head);

int main(void) {
    node *prev, *head, *p;
    head = NULL;

    for (int i = 0; i < 5; i++) {
        p = malloc(sizeof(node));
        printf("Enter number\n");
        scanf("%i", &p->data);
        p->next = NULL;
        if (head == NULL)
            head = p;
        else
            prev->next = p;
        prev = p;
    }
    deleteList(&head);
    printList(head);
    free(p);
    return 0;
}

void printList(node *head) {
    if (head == NULL) {
        printf("\nNULL\n");  
    } else {
        printf("\n%i", head->data);
        printList(head->next);
    }        
}

void deleteList(node **head) {
    node *cur = *head;
    node *nxt;

    while (cur != NULL) {
        nxt = cur->next;
        free(cur);
        cur = nxt;
    }
    *head = NULL;    
}

【问题讨论】:

  • 你确定吗?它对我显示为空
  • 添加deleteListe后是否重新编译了代码?
  • free(p); 似乎双倍释放(最后分配的 p 值存储为列表的一部分)并导致 UB。您应该将 p 设为本地循环。

标签: c linked-list


【解决方案1】:

您的代码大部分是正确的:

  • main() 末尾有一个额外的free(p); 导致未定义的行为,因为该节点已被deleteList() 释放。
  • 您应该检查malloc()scanf() 的返回值,以避免在分配内存失败或从输入流转换整数失败时出现未定义的行为。

除了这些问题,代码在释放列表后应该总是打印NULL

这是一个改进的版本:

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

typedef struct node {
    int data;
    struct node *next;
} node;

void deleteList(node **head);   
void printList(const node *head);

int main(void) {
    node *head = NULL;
    node *prev = NULL;

    for (int i = 0; i < 5; i++) {
        node *p = malloc(sizeof(node));
        if (p == NULL)
            return 1;
        printf("Enter number\n");
        if (scanf("%i", &p->data) != 1)
            return 1;
        p->next = NULL;
        if (head == NULL)
            head = p;
        else
            prev->next = p;
        prev = p;
    }
    deleteList(&head);
    printList(head);
    return 0;
}

void printList(const node *head) {
    if (head == NULL) {
        printf("NULL\n\n");
    } else {
        printf("%i\n", head->data);
        printList(head->next);
    }
}

void deleteList(node **head) {
    node *cur = *head;

    while (cur != NULL) {
        node *nxt = cur->next;
        free(cur);
        cur = nxt;
    }
    *head = NULL;    
}

【讨论】:

    猜你喜欢
    • 2010-10-24
    • 1970-01-01
    • 2016-03-31
    • 2017-08-16
    • 1970-01-01
    • 2017-10-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多