繁体   English   中英

一种使用C删除链表中元素的方法

[英]A method to delete the elements in a linkedlist using C

因此,我被要求提出一种清空整个链表的方法。

这就是我现在所拥有的,而且我不知道为什么它不起作用:

void deleteList(){



    }

您的函数需要传递到列表的开头,即可以对其进行操作的struct node *head 然后,您可以使用它代替current来跟踪当前磁头。

void deleteList(struct node *head){

    struct node* next;

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

编辑:

由于列表头是全局变量,因此您可以执行以下操作:

struct node *head;   // Initialized elsewhere

void deleteList(){

    struct node* current = head;
    struct node* next;

    while (current != NULL) {
        next = current->next;
        free(current);
        current = next;
    }
}

您的函数永远不会将“当前”分配给任何节点。 因此,您的while循环永远不会运行,因为“当前”实际上始终等于NULL( 希望是 ,实际上它是未定义的,可能会导致非常奇怪的行为)。 总是跳过循环。 尝试将列表的第一个节点作为参数传递给函数:

void deleteList(struct node * start) {

    //"start" points to the first node in the list, point "current" at it
    struct node * current = start;
    struct node * next;

    while (current != NULL) {
       next = current->next;
       //what's this pop doing?  It seems unnecessary to the logic here
       pop(next);
       //free "current" and then point "current" at "next"
       free(current); 
       current = next;
    }
}

这还允许您通过“开始”要在其上开始释放的节点来释放列表末尾的任意段。 它不必是第一个节点。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM