Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
170 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

1 Answer

0 votes
by (71.8m points)

Your else part should be like this

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...