繁体   English   中英

删除链表中的第一个节点

[英]Deleting the first node in a linked list

我正在尝试删除链接列表中的第一个节点,但不确定如何去做。 我的链表如下所示

typedef struct availableForRent{
   int milage;
   char plateNum[8];
   struct availableForRent * next;
} availablreForRent;

我的链表的初始节点完全像这样硬编码

struct availableForRent * head = NULL;
head = malloc(sizeof(struct availableForRent));
head->milage = 190000;
fillString(head->plateNum);
head->next = NULL;

fillString仅获取用户输入并将其放置在数组中

我通过这样的推送功能将成员添加到列表中

void pushAvailable(struct availableForRent * head) {
   struct availableForRent * current = head;
   while (current->next != NULL) {
      current = current->next;
   }

   current->next = malloc(sizeof(struct availableForRent));
   printf("Enter a milage amount: ");
   scanf("%d", &current->next->milage);
   fillString(current->next->plateNum);
   current->next->next = NULL;
}

我删除第一个成员的功能看起来像这样

struct availableForRent * next_node = *head;

if (next_node->next == NULL) {
   printf("Cannot remove member as it is the only data in the list!\n");
   return;
}

next_node = next_node->next;
free(*head);
*head = next_node;

当我运行程序时,收到此错误消息,

rentalQ1(2799,0x7fff9d09b380) malloc: *** error for object 0x7ffee8f62a08: pointer being freed was not allocated
*** set a breakpoint in malloc_error_break to debug
Abort trap: 6

这是否意味着我要释放的节点不存在或其他?

看来,不分配next_node是我的问题。

next_node = malloc(sizeof(struct availableForRent));

暂无
暂无

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

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