从动态链接列表中删除节点

时间:2014-11-22 01:02:49

标签: c linked-list nodes singly-linked-list

我正在编写一个程序,在为字符串和节点分配内存时将字符串保存到链表中。我的插入和搜索功能完美运行,但我似乎无法使我的删除功能正常工作。它似乎没有从节点中删除信息,但我不知道该设置是什么以及什么是免费的。任何帮助都会受到欢迎,即使它只是一个暗示。

我的节点和列表结构

typedef struct listNode {               //simple linked list   structure
struct listNode *next;                  //address to next
char *data;                            //data
} NODE;

typedef struct ListStruct {
   NODE *head;                         //head node for iterating
} LIST;

这是我目前删除节点的非工作版本

void deleteNode(LIST *list, char *string){          // passed linked list and string to find
NODE *prev, *curr, *temp;                       //variables init
//int compare;                              // for strcmp if needed
prev = NULL;                                //set prev to null
curr = list->head;                          //set current to the head of the list
while(curr != NULL){                            //while the current node is not null
if(strcmp(curr->data,string) == 0){         //check for the proper string 
    temp = curr;                            //set temp to current node to be deleted
    temp->data = strcpy(curr->data);        //copy data so free is possible
    prev->next = temp;                     //set the prev to temp
    free(curr->data);                      //free malloc'd data
    free(curr);                           //free malloc'd node
    curr = temp;                          //set curr back to temp
}
else{                               //if string isn't found at current
    prev = curr;                        //set previous to current
    curr = curr->next;                  //and current to current.next
}   

}
}//done

我知道错误是当我找到合适的字符串但我不能为我的生活弄清楚什么是错的。希望尽快收到你的回复,并一如既往地感谢你。

1 个答案:

答案 0 :(得分:3)

您可能希望稍微更新if块:

if(strcmp(curr->data,string) == 0){         //check for the proper string 
  temp = curr;                            //set temp to current node to be deleted
  if (prev == NULL)                         // if the first node is the one to be deleted
    list->head = curr->next;
  else
    prev->next = curr->next;                //set prev next pointer to curr next node
  curr = curr->next;                      //curr updated
  free(temp->data);                      //free malloc'd data
  free(temp);                           //free malloc'd node

  break;   //assume there is only one unique string in the link list
}