如何创建删除节点功能?

时间:2012-05-05 06:05:21

标签: 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
}

我在删除节点功能中只有一个问题

3 个答案:

答案 0 :(得分: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;
    }
  }
}

答案 1 :(得分: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);
}

答案 2 :(得分: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

你应该做头=头 - &gt;下

另外,如果“head”是唯一保留在链接列表前面的东西,那么使head = head-&gt; next会导致你丢失部分列表。我建议创建一个临时指针,使temp = head。然后遍历临时指针。