首页 > 解决方案 > 为什么带有双指针的链表会导致错误?

问题描述

我问你一个问题是因为我做的任务没有成功。该结构是一个普通的链表,在main中声明头指针,并将头指针的地址值作为参数传递给函数。全局变量 top 用于确定当前数据的位置。

当前下面的代码在执行时将仅检测错误。

结构:

struct ListNode{
    int data;
    struct ListNode* link;
};
int top = 0;

代码:

void DisplayList(ListNode** head){
    if(*head == NULL){
        printf("List = Empty\n");
    }
    else{
        printf("List = ");
        for(;(*head) != NULL; *head = (*head)->link){
            printf("%d ",(*head)->data);
        }
    }
    printf("\n");
}

void AddList(ListNode** head){
    ListNode* temp = (ListNode*)malloc(sizeof(ListNode));
    int num;
    printf("Data register) ");
    scanf("%d",&num);
    temp->data = num;
    temp->link = NULL;
    top++;

    if(*head == NULL){  
        *head = temp;
    }
    else{
        for(;(*head)->link != NULL; *head = (*head)->link){}    
        (*head)->link = temp;
    }
    DisplayList(head);
}

预期结果:

数据寄存器)10 列表 = 10

数据寄存器) 20 列表 = 10 20

数据寄存器) 30 列表 = 10 20 30


标签: clinked-listdouble-pointer

解决方案


您不应该*head在循环中进行修改。您需要使用局部变量来单步执行列表,否则您将更改调用者的变量以指向列表的末尾。

void DisplayList(ListNode** head){
    if(*head == NULL){
        printf("List = Empty\n");
    }
    else{
        printf("List = ");
        for(ListNode *step = *head;step != NULL; step = step->link){
            printf("%d ",step->data);
        }
    }
    printf("\n");
}

void AddList(ListNode** head){
    ListNode* temp = (ListNode*)malloc(sizeof(ListNode));
    int num;
    printf("Data register) ");
    scanf("%d",&num);
    temp->data = num;
    temp->link = NULL;
    top++;

    if(*head == NULL){  
        *head = temp;
    }
    else{
        ListNode *step = *head;
        for(;step->link != NULL; step = step->link){}    
        step->link = temp;
    }
    DisplayList(head);
}

推荐阅读