c - 从链表中删除一个节点

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

最佳答案

以下代码解决了目的:

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

关于c - 从链表中删除一个节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20272446/

相关文章:

c - C中的节点和链表语法

c++ - 如何包装std::vector以在纯C中使用

c - 找出两百万以下的所有质数之和。欧拉计划,C

c++ - "long long = int + int "先计算,再类型转换?

c++ - 链表增加节点数

java - 递归反向链表,最后一个节点应该指向null吗?

c - 在 C 程序中禁用中断

c - 使用较大数组初始化字符数组时的行为

java - 尝试使用递归创建 removeLastElement

c - 链表内存问题