【问题标题】:Delete a node from a linked list [duplicate]从链表中删除节点[重复]
【发布时间】:2013-12-14 20:44:42
【问题描述】:

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

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;
}

【问题讨论】:

  • 正确链接它们,它应该可以工作。
  • 你尝试过的一切是什么?随意发布代码。 (不,我们不会写你的作业。)
  • @BitFiddlingCodeMonkey 不,他没有。
  • @BitFiddlingCodeMonkey :不需要prev 链接。你也可以从单链表中删除一个节点。
  • @Denim Idea 太好了,他需要被告知两次。

标签: c linked-list


【解决方案1】:

下面的代码解决了这个目的:

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;
}

【讨论】:

  • 比我想做的好多了,谢谢。
  • 不错的代码!但是,像这样把它倒在盘子里真的有用吗?
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 2019-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-08
    • 1970-01-01
    • 2017-10-21
    • 2013-08-30
    相关资源
    最近更新 更多