C从链接列表中删除节点

时间:2013-08-27 12:53:02

标签: c pointers linked-list nodes

如何从链表中删除节点?

这是我的代码:

void RemoveNode(Node * node, Node ** head) {
    if (strcmp(node->state, (*(*head)->next).state) == 0) {
        Node * temp = *head;
        *head = (*head)->next;
        free(temp);
        return;
    }

    Node * current = (*head)->next;
    Node * previous = *head;
    while (current != NULL && previous != NULL) {
        if (strcmp(node->state, (*current->next).state) == 0) {
            Node * temp = current;
            previous->next = current->next;
            free(temp);
            return;
        }
        current = current->next;
        previous = previous->next;
    }
    return;
}

但我不断遇到段错误。

我觉得我做的事情很愚蠢......有什么想法吗?

2 个答案:

答案 0 :(得分:5)

我的猜测:

void RemoveNode(Node * node, Node ** head) {
    if (strcmp(node->state, ((*head)->state) == 0) {
        Node * temp = *head;
        *head = (*head)->next;
        free(temp);
        return;
    }

    Node * current = (*head)->next;
    Node * previous = *head;
    while (current != NULL && previous != NULL) {
        if (strcmp(node->state, current->state) == 0) {
            Node * temp = current;
            previous->next = current->next;
            free(temp);
            return;
        }
        previous = current;
        current = current->next;
    }
    return;
}

答案 1 :(得分:2)

我建议您尝试使用递归执行此操作,以避免需要“双指针”。它将极大地简化逻辑。 This link有一个很好的解释和实现递归执行此操作。如果您尝试从空链接列表中删除节点,则此功能甚至可以使用。

Node *ListDelete(Node *currP, State value)
{
  /* See if we are at end of list. */
  if (currP == NULL)
    return NULL;

  /*
   * Check to see if current node is one
   * to be deleted.
   */
  if (currP->state == value) {
    Node *tempNextP;

    /* Save the next pointer in the node. */
    tempNextP = currP->next;

    /* Deallocate the node. */
    free(currP);

    /*
     * Return the NEW pointer to where we
     * were called from.  I.e., the pointer
     * the previous call will use to "skip
     * over" the removed node.
     */
    return tempNextP;
  }

  /*
   * -------------- RECURSION-------------------
   * Check the rest of the list, fixing the next
   * pointer in case the next node is the one
   * removed.
   */
  currP->next = ListDelete(currP->next, value);


  /*
   * Return the pointer to where we were called
   * from.  Since we did not remove this node it
   * will be the same.
   */
  return currP;
}