我刚刚开始学习 C 并且是一个初学者。今天在学校,我们学习了链表,我能够编写一个代码......幸运的是它运行没有错误。
#include<stdio.h>
#include<stdlib.h>
struct node
{
    int data;
    struct node *next;
}*head;//*temp;
void create(struct node **h,int num)
{
    int i;
    struct node *temp=*h;
    for(i=0;;i++)
    {
        if(i>=num)
        break;
        temp->data=i;
        temp->next=malloc(sizeof(struct node));
        temp=temp->next;
    }
    temp->next=NULL;
}
    void display(struct node **h)
{   
    struct node *temp=*h;
    while(temp->next!=NULL)
    {
        printf("%d->",temp->data);
        temp=temp->next;
    }
    printf("\b\b  \b\b");
}
void append_end(struct node **h,int val)
{
    struct node *temp=*h,*temp1;
    //printf("'%d'",val);
    while(temp->next!=NULL)
    temp=temp->next;
    temp1=malloc(sizeof(struct node));
    temp1->data=val;
    temp1->next=NULL;
    temp->next=temp1;
}
void free_list(struct node **h)
{
    struct node *temp=*h,*tail;
    while(temp->next!=NULL)
    {
        tail=temp;
        temp=temp->next;
        free(tail);
    }
    h=NULL;
}
int main()
{
    head=malloc(sizeof(struct node));
    int i,num;
    scanf("%d",&num);
    create(&head,num);
    //display(&head);
    append_end(&head,5);
    append_end(&head,6);
    display(&head);
    /*temp=head;
    while(temp->next!=NULL)
    temp=temp->next;
    printf("%d",temp->data);*/
    free_list(&head);
    return 0;
}
对于 4 的输入,预期的输出应该是 0->1->2->3->5->6
但相反,我得到 0->1->2->3->(一些垃圾值)->5
如果有人能指出我的错误和/或链接到任何可能有助于我清楚地理解该主题的文章,我会很高兴。
提前致谢。