c - c : Function which deletes every second element of linked list 中的指针

标签 c pointers linked-list

我想写一个函数,它获取一个指向链表头的指针,并从链表中每隔一个成员删除一次。 List 是 element 类型的链接元素:

typedef struct element{
    int num;
    struct element* next;
}element;

我是所有这些指针算法的新手,所以我不确定我写的是否正确:

 void deletdscnds(element* head) {
    element* curr;
    head=head->next; //Skipping the dummy head//

    while (head!=NULL) {
        if (head->next==NULL) 
            return;

            else {
                curr=head;
                head=head->next->next; //worst case I'll reach NULL and not a next of a null//
                curr->next=head;
            }
        }
    }

我一直在修改它,因为我一直在发现错误。能否请您指出任何可能的错误?

最佳答案

如果您根据节点对来考虑您的链表,则该算法会简单得多。循环的每次迭代都应处理两个节点 - headhead->next,并使 head 等于 head->next ->next 退出时。同样重要的是不要忘记删除中间节点,如果您要将它从列表中删除,否则您将看到内存泄漏。

while (head && head->next) {
    // Store a pointer to the item we're about to cut out
    element *tmp = head->next;
    // Skip the item we're cutting out
    head->next = head->next->next;
    // Prepare the head for the next iteration
    head = head->next;
    // Free the item that's no longer in the list
    free(tmp);
}

关于c - c : Function which deletes every second element of linked list 中的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11566138/

相关文章:

c - 执行默认信号处理程序

c - 我做了什么?指向 double 指针的指针?

c - 从c中的文件填充指针数组

c - 从文件读取到 LinkedList C 时,最终字段为 NULL

c++ - 使用递归查找单个链表中倒数第 n 个节点

c - realloc 是否在重新分配的字符串中包含\0?

c - 在 C 中迭代链表时空检查行为不正确

java - 对链接列表进行排序

c++ - C/C++ 的选项解析器?

c - 我的无符号短指针返回意外结果。为什么?