C programming Linked Lists delete node at position N

前端 未结 5 557
猫巷女王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:58

    // Remove list's node located at specified position.
    // Arguments:
    //  head -- list's head
    //  pos -- index of a node to be removed (1-based!!!)
    
    struct node* DeleteNode(struct node* head, int pos) 
    {
    
        struct node* node;
        struct node* prev;
        int length;
        int i;
    
        printf("DeleteNode: position = %d \nBefore: ", pos);
        PrintList(head);
    
        // Check position's lower bound. Should be >= 1
        if(pos <= 0) { //node does NOT exist
            printf("ERROR: Node does not exist!\n");
            return head;
        }
    
        // Seek to the specified node, and keep track of previous node.
        // We need previous node to remove specified node from the list.
    
        for(i=1, prev = 0, node = head; i < pos && node != 0; i++) {
            prev = node;
            node = node->next;
        }
    
        // Out of range
        if(0 == node) {
            printf("ERROR: Index out of bounds!\n");
            return head;
        }
    
        // @node points to a list's node located at index pos 
        // @prev points to a previous node.
    
        // Remove current node from the list.
        if(0 == prev) {
            head = node->next;
        }
        else {
            prev->next = node->next;
        }
        free(node);
    
        return head;   
    }
    

提交回复
热议问题