函数中的 add() 只向列表中添加两个元素

The add() in function only add two elements to the list

这里这个函数应该处理单链表中的数据条目,如果列表中没有项目,它会将它添加到头部,然后再往前,这个 add () 函数在 while 循环中被调用,直到用户想要继续。但这只是添加前两个数据,不适用于列表的其余部分

struct node{
int data;
struct node *nextptr;
}*head;

 int add()
    {
        struct node *ptr,*tmp;
        int value;
        ptr=malloc(sizeof(struct node));
        if(ptr==NULL)
        {
            printf("MEMORY ALLOCATION FAILED ");
        }
        else
        {
            printf("ENTER THE VALUE YOU WANT TO ENTER ");
            scanf("%d",&value);
            if(head==NULL)
            {
                ptr->data=value;
                ptr->nextptr=NULL;
                head=ptr;
            }
            else
            {   tmp=head;
                ptr->data=value;
                ptr->nextptr=NULL;
                tmp->nextptr=ptr;
                ptr=ptr->nextptr;
                tmp=tmp->nextptr;
            }
        }
        return 0;
    }

请尝试说出这个方法中的问题,我遇到过不同的方法来做同样的事情,但我只需要知道为什么它不能这样实现。

你的其他部分应该是这样的

else {
    // asign head to tmp
    tmp = head;

    // traverse till you reach NULL
    while(tmp->nextptr)
        tmp = tmp->nextptr;

    // add new element when you reach NULL
    tmp->nextptr = ptr;
}