Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
468 views
in Technique[技术] by (71.8m points)

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

Here this function is supposed to take care of entry of data in a Singly-Linked List, If there is no item in the list it adds it to the head and after that onwards, This add() function is called on a while loop till the user wants to continue. But this is only adding the first two data and is not working for the rest of the list

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;
    }

Kindly try to tell the problem in this method, I have came across different ways to do the same but I just need to know why it can't be implemented this way.

question from:https://stackoverflow.com/questions/65651160/the-add-in-function-only-add-two-elements-to-the-list

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

Please log in or register to reply this article.

OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...