c - 如何实现删除节点的功能?

标签 c

我一直在创建一个对我来说正常工作的node_add函数, 但我很难创建一个 node_delete 节点。

这是我写的:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdlib.h>
typedef struct friend // The struct
{
   char *name; 
   int age;
   char gender; 
   struct friend* next; // A pointer that points to the next node in the linked list
}friend;
void node_delete(); // The deleting node function
friend* head; // Definging the head of the linked list
void node_delete() // Deleting a node
{
 char name[256];
 printf ("Please enter the friend's name you want to delete: \n");
 fgets (name, 256, stdin);
 fgets (name, 256, stdin); // Getting the name of the person that the user wants to delete
 while (head -> next != NULL) // As long the node isnt the last one
 {
       if (0 == (strcmp(head -> name, name))) // If the name that the user entered matchs a name in the linked list,
       { // It'll skip it
             head -> next = head -> next -> next; // Deletes a node from the linked list
       }
       head -> next; // Going to the next node
}
 free(head); // Freeing the deleted node
}

我只有删除节点功能有问题

最佳答案

if (head) {
  if (strcmp(head->name, name) == 0) {
    to_free = head;
    head = head->next;
    free(to_free);
  } else {
    list = head;
    while (list->next) {
      if (strcmp(list->next->name, name) == 0) {
        to_free = list->next;
        list->next = list->next->next;
        free(to_free);
        break; // if only one
      }
      list = list->next;
    }
  }
}

关于c - 如何实现删除节点的功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10459332/

相关文章:

c - 函数中预期的声明说明符错误

c - 如何将 char 数组中的 base10 十进制(大端)转换为二进制(小端的十六进制)

c - linux内核模块中的最大指针/数组大小

c - C中递归函数枚举并返回二维数组n选k的所有组合

c - 来自scala的c中的动态调度

c++ - 是否有从代码库中删除第三方 C 和 C++ 库的好技巧或工具? (OS X 或 Linux)

在C中将字符数字转换为相应的整数

c - 在特定函数中使用 printf 访问 C 中的链表时出现问题(访问内存问题)

c - 按位 & 和 I

c - 如何打印另一个进程的信息?