C programming Linked Lists delete node at position N

前端 未结 5 569
猫巷女王i
猫巷女王i 2020-12-18 08:16

EDIT: Figured out the problem. Also if you found this through google or another search engine here is where I went wrong and how to fix it.

My delet

5条回答
  •  北荒
    北荒 (楼主)
    2020-12-18 08:54

    In your code, you have the line

    newNode->next;
    

    in your for loop. That operation doesn't do anything.

    You also have

    newNode-> = NULL;
    

    which is not valid C, and I have no idea how you got that to compile.

    But really, don't use that loop. A linked list is one of the most basic recursive data structures. As a result, almost all algorithms manipulating them are most elegant as a recursive solution.

    typedef struct node node_t;
    
    node_t* delete_at_index(node_t* head, unsigned i)
    {
        node_t* next;
    
        if(head == NULL)
            return head;
    
        next = head->next;
    
        return i == 0
                 ? (free(head), next)                                 /* If i == 0, the first element needs to die. Do it. */
                 : (head->next = delete_at_index(next, i - 1), head); /* If it isn't the first element, we recursively check the rest. */
    }
    

提交回复
热议问题