【问题标题】:Removing node from Dynamically linked list从动态链接列表中删除节点
【发布时间】:2015-01-20 06:43:23
【问题描述】:

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

我的节点和列表结构

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

我知道错误在于我找到了正确的字符串,但我终其一生都无法找出问题所在。希望尽快收到某人的来信,并一如既往地感谢您。

【问题讨论】:

  • 我建议使函数更加模块化。意味着搜索和比较部分作为一个函数,将返回一个节点。然后删除将只接受一个节点作为参数,并释放它的字符串和节点本身。从而使其更易于调试、更易于维护和更易于理解。

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


【解决方案1】:

您可能想稍微更新一下 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
}

【讨论】:

  • 一个更正:应该是list->head而不是list->header
  • 仍然无法工作,但我会使用这个和一些 printf,看看我是否能让她工作。感谢您的帮助。
  • @Chris,请提供一些可能有助于调试的输出。
  • @Dere0405 我有点不好意思说,但我忘了取消注释我调用该函数的行,它的效果很棒。非常感谢您的帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-08
  • 2019-09-11
  • 2015-11-14
  • 2021-05-05
相关资源
最近更新 更多