昨晚我的C代码中发现了一些奇怪的行为。
我有一些用于创建和操作C链表的基本功能。
我的插件在第n个位置的行为虽然很奇怪。

第一个版本工作正常,但是第二个版本根本没有插入列表中。我想念什么吗?

//This works fine
void insert_nth(struct node** head, int data, int n_pos){
    if (n_pos == 0){
        insert_top(head, data);
        return;
    }
    struct node* current = *head;
    for(int i = 0; i < n_pos - 1 ; i++){
        if(current == NULL) return;
        else current = current->next;
    }
    if(current == NULL) return;
    insert_top(&(current->next), data);
}

//This doesn't insert at all
void insert_nth(struct node** head, int data, int n_pos){
    if (n_pos == 0){
        insert_top(head, data);
        return;
    }
    struct node* current = *head;
    for(int i = 0; i < n_pos ; i++){
        if(current == NULL) return;
        else current = current->next;
    }
    if(current == NULL) return;
    insert_top(&(current), data);
}


这是我要参考的其余功能。

int main(){
    struct node* head = NULL;
    build_rand_list(&head);
    list_print(&head);
    return 0;
}

void list_print(struct node** head){
    printf("List size is %d: List: ", list_length(head));
    for(struct node* current = *head; current!= NULL; current = current->next)
        printf("%d ", current->data);
    printf("\n");
}

void build_rand_list(struct node** head){
    //Assume head is NULL
    assert(*head == NULL);
    srand(time(NULL));
    for (int i = 0; i < 10; i++){
        int random_num = rand() % 11;
        insert_end(head, random_num);
    }
}

void insert_top(struct node** head, int data){
    struct node *new_node = (struct node *)malloc(sizeof(struct node));
    new_node->data = data;
    new_node->next = *head;
    *head = new_node;
}

最佳答案

&(current)是局部变量的地址。
&(current->next)是列表中节点内部的指针的地址。

修改局部变量current(最终会执行insert_top的操作)对列表的节点没有影响。

关于c - 链表插入行为,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/39662906/

10-11 22:35
查看更多