此代码在调用创建函数后需要两个输入

this code expects two input after calling create function

//linked list
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#include <conio.h>

struct node
{
    int data;
    struct node *next;
};

struct node *head = NULL;

struct node *create(struct node *head);

int main()
{
    int n;
    printf("enter your slection");
    printf("\n 1.create a linked list");
    scanf("%d", &n);

    switch (n)
    {
        case 1:
        head = create(head);
        printf("linked list has been created");
        break;

        default:
        break;
    }

    return 0;
}

struct node *create(struct node *head)
{
    struct node *newnode, *ptr;
    int num;
    printf("enter data of node");
    scanf("%d ",&num);
    newnode = (struct node *)malloc(sizeof(struct node *));

    if (newnode != NULL)
    {
        head=newnode;
        newnode->data=num;
        newnode->next=NULL;
    }

    return head;
}

我不知道为什么,但在调用函数 printf 命令后,终端要求我在链表中​​输入数据,但在输入一些数据后,它再次需要一些输入。我真的不知道该尝试什么了。

问题在于您如何读取 create 中的输入:

scanf("%d ",&num);

格式字符串中的 space 匹配任意数量的白色 space 字符。因此,如果您输入一个数字后跟一个换行符,scanf 将等到您输入一个非白色 space 字符。

这可以通过从格式字符串中删除 space 来解决。

scanf("%d",&num);