withinboy
withinboy

Reputation: 33

how to add node to the end(singly linked list)

void addToEnd()
{
    newnode = (struct node*)malloc(sizeof(struct node));

    printf ("Enter the customer name :");
    scanf ("%s", newnode->cName);

    printf ("\nEnter customer number :");
    scanf ("%d", &newnode->cNumber);

    printf ("\nEnter transaction description :");
    scanf ("%s", newnode->tDescrip);

    newnode->next = NULL;
    if(list==NULL)
        list = newnode;
    else if (list != NULL && newnode < list)
    {
        newnode->next = list;
        list = newnode;
    }
    else
    {
        temp = list;
        while (temp != NULL)
        {
            if (newnode > temp)
            {
                prev = temp;
                temp = temp->next;
            }
        }
        newnode->next = prev->next;
        prev->next = newnode;
    }
}

i tried this code, but tis code is just add to start but not to end, how am i suppose to add the node to the end?

Upvotes: 0

Views: 3778

Answers (2)

Lucifer
Lucifer

Reputation: 29642

Please study the following append function for adding a node in to Linked List

append( int num )
{
    struct node *temp,*r;
    /* CREATING A NODE AND ASSIGNING A VALUE TO IT */

    temp= (struct node *)malloc(sizeof(struct node));
    temp->data=num;
    r=(struct node *)p;

    if (p == NULL) /* IF LIST IS EMPTY CREATE FIRST NODE */
    {
        p=temp;
        p->next =NULL;
    }
    else
    { /* GO TO LAST AND ADD*/

        while( r->next != NULL)
            r=r->next;
            r->next =temp;
            r=temp;
            r->next=NULL;
    }
}/* ADD A NEW NODE AT BEGINNING */

Upvotes: 0

Joop Eggen
Joop Eggen

Reputation: 109557

Let's see, whether the following isn't as easily understood.

Simply change the pointer:

struct node** tail = &list;
while (*tail != NULL) {
    tail = &((*tail)->next);
}
*tail = newnode;

Upvotes: 2

Related Questions