链接列表节点链接问题

时间:2016-03-03 06:07:52

标签: c

我试图创建链表,但节点没有正确链接。我在代码中遗漏了一些内容。我不知道它是什么。

typedef struct sllist{
    int x;
    struct sllist *next;
} slilist;

slilist *head=NULL, *tail=NULL;

void add_to_List(int val){
    slilist *temp = malloc(sizeof(slilist));
    temp->x = val;
    temp->next = NULL;
    if(!head){
        head = temp;
        tail = temp;
    }else{
        tail->next = temp;
    }
}

int main()
{
    int y;
    for(y = 0; y<10; y++)
        add_to_List(y);

    while(head){
        printf("%d\n",head->x);
        head=head->next;
    }
    return 0;
}

我的输出是:

0
9

3 个答案:

答案 0 :(得分:2)

尝试改变:

if(!head) {
    head=temp;
    tail=temp;
} else {
    tail->next=temp;
    tail = temp;
}

事实上,您忘记在tail声明中更改else

tail = temp;

答案 1 :(得分:2)

您无法更新tail,因此新元素都在头部之后链接。

void add_to_List(int val){
    slilist *temp = malloc(sizeof(slilist));
    temp->x=val;
    temp->next=NULL;
    if(!head){
        head=temp;
        tail=temp;
    }else{
        tail->next=temp;
        tail=tail->next; /* add this line */
    }
}

此外,您应free()通过malloc()分配的所有内容。

int main()
{
    int y;
    for(y=0; y<10; y++)
        add_to_List(y);

    while(head){
        slilist *head_bak = head; /* add this line */
        printf("%d\n",head->x);
        head=head->next;
        free(head_bak); /* add this line */
    }
    return 0;
}

答案 2 :(得分:0)

您可以添加以下代码:

typedef struct sllist{
    int x;
    struct sllist *next;
} slilist;

slilist *head=NULL, *tail=NULL;

void add_to_List(int val){
    slilist *temp = malloc(sizeof(slilist));
    temp->x = val;
    temp->next = NULL;
    if(!head){
        head = temp;
        tail = temp;
    }else{
        while (tail->next !=NULL)
    {
        tail = tail->next;
    }
    tail->next = temp;
    }
}

int main()
{
    int y;
    for(y = 0; y<10; y++)
        add_to_List(y);

    while(head){
        printf("%d\n",head->x);
        head=head->next;
    }
    return 0;
}
    
相关问题