c - 在C中的双向链表中删除头节点的问题

标签 c pointers doubly-linked-list

我正在尝试用 C 实现一个双向链表。在编写代码时,我在尝试删除列表的第一个元素时遇到了问题。

这是一个说明问题的玩具示例:

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

 typedef struct Node{
     struct Node * next;
     struct Node * previous;
     int data;
 }Node;


 Node* create_dll(int array[], int arrSize){
     Node *current = (Node*)malloc(sizeof(Node));
     current->next = NULL;
     current->data = array[0];
     for(int i = 1; i < arrSize; i++){
         Node *temp = (Node*)malloc(sizeof(Node));
         temp->data = array[i];
         temp->next = current;
         current->previous  = temp;
         current = temp;
     }
     current->previous = NULL; 
     return current;
 }
 void print_dll(Node *head){
     if(head != NULL){
         Node *current = head;
         while(current!=NULL){
         printf("%d \t", current ->data);
             current = current->next;
         }
     }
     puts(" ");
 }

 void delete_head(Node *head){
     Node *current = head;
     head = head->next;
     //head ->previous = NULL;
     free(current);
 }
 void kill(Node *head){
     Node *current = head;
     while (current != NULL){
         Node *previous = current;
         current = current ->next;
         free(previous);
     }
 }

 int main(){
     int array [] = {1, 2, 3, 4, 5};
     int arrSize = 5;

     Node *head;

     head = create_dll(array, 5);

     print_dll(head);

     delete_head(head);
     print_dll(head);

     kill(head);
     return 0;

}

每当我尝试在 main 中运行代码时,它会创建一个 DLL,然后打印其中的内容,然后尝试删除第一个节点,然后再次打印列表,我得到以下结果:

    5   4   3   2   1    
    5    

现在,我知道一种解决方法是制作 head一个全局变量,但这在代码的其他部分会有问题,而且我真的不想走那条路。我也不想修改任何函数头或 main 中的任何内容。

我确实通过使用虚拟节点实现 DLL 来实现它 head总是指向,但我相信这个实现有一个简单的修复可以避免这一切。

基本上,如果我能改变什么head指向 delete_head功能 并将此更改反射(reflect)在主要功能中,这将是一个解决方案。否则,我很乐意理解为什么这段代码无法执行我想要的操作。

非常感谢任何帮助!谢谢!

最佳答案

问题是,当您调用 delete_head 时,C 参数传递是按值传递的,因此 head 在返回时不会更改。你需要像这样实现它:

void delete_head(Node **head){
            Node *current = *head;
            *head = current->next;
            //head ->previous = NULL;
            free(current);
}

并这样调用它:delete_head(&head);

关于c - 在C中的双向链表中删除头节点的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55132208/

相关文章:

cppcheck 检测到资源泄漏 - 漏报?

c++ - 验证 C/C++ 有符号右移是否是特定编译器的算术?

c++ - 如何获得给定进程的窗口站?

C++ 对两个成对整数数组的 "percentage"进行排序

c - Trie树并找到出现次数最多的n个单词,指针

c - 我有一个节点哈希表。如何打印哈希表中每个节点的每个单独值?

c++ - 访问对象的 vector 时发生读取冲突

algorithm - 排序双链表插入中的递归

C - 无法从 void 指针访问结构元素值

c - C 中的链表 – 方法