从链接列表中删除节点

时间:2013-11-28 18:08:25

标签: c linked-list

我想要做的是创建一个函数,它将列表作为输入和数字,并将删除该列表中与该特定数字相等的节点。所以,如果我有一个链表,可以说:

struct num // list 1
{
        char *val;
        struct num *next;
};

我已经在该列表中添加了4个项目,我希望能够删除第三个项目并使用现在的3个项目取回新列表。到目前为止我尝试过的所有东西虽然不能正常工作,但我认为因为我删除了其中一个后没有正确链接其余项目。

因为你坚持这里是我现在所拥有的

struct num1 *temp;
    temp = head;

struct num1* deletend(int del){
    for ( int i = 0; i < listSize; i++)
    {   
            if (i == del){
                free(temp);
            }
            temp = temp->next;
    }
    return temp;
}

2 个答案:

答案 0 :(得分:0)

您需要将指向前一个成员的指针保留为已删除的成员。然后用指向已删除成员中的下一个成员的指针替换已删除成员的前一个指针。

答案 1 :(得分:0)

以下代码解决了目的:

typedef struct num numNode;  // typedef to escape repeated struct num

numNode* delete_item(numNode* startNode, int position)
{
    int pos = 0;
    numNode* current = NULL;
    numNode* prev = NULL;

    if ((start == NULL) || (position == 0)) // if empty list or 0th item deletion, return the list as it is
        return start;
    else if (position == 1)    // if delete first item,
    {
        current = start;       // this node to be deleted
        start = start->next;   // Set start to the next item

        free current;
        current = NULL;        // delete the node

        return start;
    }
    else
    {
        prev = start;           // this will mark the previous node
        current = prev->next;   // this will mark the current node
        pos = 2;                // position 0, 1 taken care of
    }

    while ((current != NULL))
    {
        if (pos == position)    
        {
            prev->next = current->next;  
            free current;
            current = NULL;
            break;
        }
        pos++;
    }

    return start;
}