-1

我一直在创建一个 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
}

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

4

3 回答 3

1
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;
    }
  }
}
于 2012-05-05T07:16:25.093 回答
1
struct friend **tmp = &head;
while (*tmp != NULL && (0 != (strcmp((*tmp)->name, name)))) {
  tmp = &((*tmp)->next);
}
if (*tmp) {
  struct friend *freeme = (*tmp);
  (*tmp) = (*tmp)->next;
  free(freeme);
}
于 2012-05-05T08:05:43.663 回答
0

仔细看看这个。

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
}

它实际上并没有遍历链表

  head -> next; // Going to the next node

你可能应该让 head = head -> next

此外,如果“head”是唯一保持在链表前面的东西,那么设置 head = head->next 将导致您丢失链表的一部分。我建议创建一个临时指针,以便 temp = head. 然后遍历临时指针。

于 2012-05-05T06:13:56.300 回答