C语言 我想从一个插入方法创建两个链表,如何多次发送对该方法的头部引用?我在运行时收到输入错误



main 和插入方法

int main()
{
    struct node *head=NULL,*head_1=NULL;
    int n,i;
    for ( i = 0; i < 5; i++)
    {
        printf("Enter the data n");
        scanf("%d",&n);
        insert(&head,n);
    }
    for (i = 0; i < 5; i++)
    {  
        printf("Enter the data n");
        scanf("%d",&n);
        insert(&head_1,n);
    }
    display(head);
    return 0;
}
 void insert(struct node **head,int a)
{
    struct node* temp,*new;
    new=(struct node*)malloc(sizeof(struct node));
    new->data=a;
    new->next=NULL;
    if(head==NULL)
    {
        (*head) = new;
        temp=new;
    }
    temp->next=new;
    temp=new;
} 

一旦我为第一个链表输入第一个数据,程序就会停止,我可以全局声明头部指针,但随后我必须声明两次插入方法。

在这里我更正了您的代码

int main()
{
    struct node *head=NULL,*head_1=NULL;
    int n,i;
    for ( i = 0; i < 5; i++)
    {
        printf("Enter the data n");
        scanf("%d",&n);
        if (insert(&head,n))    /* Check for malloc failure */
            /* Error */
    }
    for (i = 0; i < 5; i++)
    {  
        printf("Enter the data n");
        scanf("%d",&n);
        if (insert(&head_1,n))
            /* Error */
    }
    display(head);
    return 0;
}
/*
 * The insert() function adds a new element at the head of the list.
 */
int insert(struct node **head, int a)
{
    struct node *new;      /* temp is not needed */
    new=(struct node*)malloc(sizeof(struct node));
    if (!new)              /* Check for malloc fail */
        return 1;          /* Non-zero return value (error) */
    new->data=a;
    new->next = *head;     /* Save the head in new (don't care if it's NULL) */
    *head = new;           /* Update head */
    return 0;              /* All went fine */
}
/*
 * The append() function adds a new element at the end of the list.
 */
int append(struct node **head, int a)
{
    struct node *new;
    new = (struct node*)malloc(sizeof(struct node));
    if (!new)              /* Same as before */
        return 1;
    new->data = a;
    new->next = NULL;
    if (*head == NULL)     /* List doesn't exist yet */
    {
        *head = new;       /* Initialize the list */
        return 0;
    }                      /* List exists, find the end */
    struct node *actual;   /* This is what we iterate with */
    actual = *head;
    while (actual->next != NULL)
        actual = actual->next;   /* Go through the list */      
    actual->next = new;     /* Append new */
    return 0;
}

请记住始终检查malloc的回报。我选择返回 0 作为函数中的"一切正常"代码insert但如果需要,您可以反转它。我希望你明白一切,如果没有,请在评论中询问,我会添加额外的解释。

正如您在这两个示例中所看到的,两个函数的元素创建部分是相同的,这就是为什么您应该创建一些struct node *newnode(int data)函数以使代码更轻的原因。

最新更新