为什么我不能从列表中删除节点?

时间:2015-04-27 15:13:27

标签: c struct linked-list unhandled-exception

每当我尝试这样做时,我会在if语句中得到一个无法解释的异常?到目前为止的其他一切工作正常。

      void DeleteEmp(struct node* head, int tempID){
           struct node *curNode = head;
           struct node *prevNode = NULL;
           while (curNode != NULL) {
                if(curNode->empId == tempID) { // error here
                    free(curNode);
                    printf("Employee %d removed from database", tempID);
                }
                prevNode = curNode;
                curNode = curNode->next;
            }
        }

3 个答案:

答案 0 :(得分:2)

curNode之后您正在使用free

   while (curNode != NULL) {
        if(curNode->empId == tempID) { // error here
            free(curNode);
            printf("Employee %d removed from database", tempID);
        }
        prevNode = curNode;
        curNode = curNode->next; // PROBLEM HERE.
    }

也许您的意思是在致电free之后立即返回。

void DeleteEmp(struct node* head, int tempID){
   struct node *curNode = head;
   struct node *prevNode = NULL;
   while (curNode != NULL) {
      if(curNode->empId == tempID) {
         if ( prevNode == NULL )
         {
            // This means curNode is the head.
            // Since curNode is about to be deleted,
            // make the next node the head.
            head = curNode->next;
         }
         else
         {
            // Since curNode is about to be deleted,
            // change the next node of prevNode.
            prevNode->next = curNode->next;
         }

         free(curNode);
         printf("Employee %d removed from database", tempID);
         return;
      }
      prevNode = curNode;
      curNode = curNode->next;
   }
}

答案 1 :(得分:2)

您应该在释放之前从列表中删除该节点。

       while (curNode != NULL) {
            if(curNode->empId == tempID) {  
                if (prevNode){// remove the node from the list
                    prevNode->next = curNode->next;   
                }
                else{
                    head = curNode->next;
                } 
                free(curNode);
                printf("Employee %d removed from database", tempID);
                return;//assuming empId is unique return after you found it.
            }
            prevNode = curNode;
            curNode = curNode->next;
        }

答案 2 :(得分:2)

在释放节点的地方,在释放节点之前,您需要进行一些指针交换。 考虑一下这个

a->b->c->NULL

删除b应该在免费之前执行以下操作。

a->c->NULL 

请注意,特殊情况是删除c,删除导致新头的a并删除单个列表中的唯一节点。

注意类型GList和处理函数在库GObject中,使用此列表代码而不是编写和调试它可能是有意义的。