根据匹配的数据删除节点

时间:2016-08-24 20:21:18

标签: c linked-list

路线:实施以下功能以按姓氏搜索,然后从链接列表中删除第一个匹配的学生。如果找到匹配的学生,则该函数返回指向新链表的头部的指针;如果找不到匹配的学生,则列表不变,并返回链表的头部。

编译并运行此代码时,每次只删除头节点。即使名称位于列表中间或根本不在列表中,也始终删除头节点。不确定什么是错的。任何帮助将不胜感激!谢谢!

STUDENT *DeleteByLastName(STUDENT *students, char *name)
{
struct STUDENT* current = students;
struct STUDENT* previous = NULL;

while (current != NULL) {
  if (current->Lastname == name) {
     if (previous == NULL) {
        current = current->Next;
        free(students);
        students = current;
     }
     else {
        previous->Next = current->Next;
        free(current);
        current = previous->Next;
     }
  } 
  else {
     previous = current;
     current = current->Next;
  }
  return current;
}    
return NULL;

}

1 个答案:

答案 0 :(得分:0)

感谢您的提示!这是我为有兴趣的人工作的代码。

STUDENT *DeleteByLastName(STUDENT *students, char *name)
{
struct STUDENT* current;
struct STUDENT* head = students;

current = students;
int count = 0;
struct STUDENT* previous = NULL;

while (current != NULL) {
    //check for matching head and delete
    if (strcmp(current->Lastname,name) == 0 && count == 0) {
        students = current->Next;
        return students;
    }
    //If name matches but is not at the beggining of the list
    if(strcmp(current->Lastname,name) == 0) {
        previous->Next = previous->Next->Next;
        current = current->Next;
        return students;
    }
    else {
        previous = current;
        current = current->Next;
        ++count;
    }
}
return head;
}