c中的指针:删除链表的每个第二个元素的函数

Joz*_*zef 4 c pointers linked-list

我想编写一个函数,它获取指向链表头的指针,并从列表中删除每个第二个成员.List是type 元素的链接元素:

typedef struct element{
    int num;
    struct element* next;
}element;
Run Code Online (Sandbox Code Playgroud)

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

 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;
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

我不断改变它,因为我一直在发现错误.你能指出任何可能的错误吗?

das*_*ght 9

如果您根据节点对考虑链接列表,则算法会简单得多.您每次循环应该处理两个节点- 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);
}
Run Code Online (Sandbox Code Playgroud)