An Overflowed Stack
An Overflowed Stack

Reputation: 344

How to add an element to the end of a pointer list given head only?

void add_end(node** head, node* new_node)
{
    if(*head==NULL)
    {
        *head=new_node;
        new_node->next=NULL;
    }else
    {

    }
}

I'm new to C and pointer operation. So if I want to add an element to the end of the list, how could I manage it? I have tried node *temp=*head; to save the address of head without changing it. Then while(temp) { temp=temp->next}. Apparently, temp only get a shallow copy. How could I implement this function. Thank you.

Upvotes: 1

Views: 1600

Answers (1)

herohuyongtao
herohuyongtao

Reputation: 50657

You should first traverse to the end of the original list (based on last one's next is NULL). And then simply add it there.

Like this:

new_node->next = NULL;
if(*head == NULL)                // empty list
{
    *head = new_node;
}
else                            // not empty, traverse to end and add
{
    node *current = *head;
    while (current->next)       // <- traverse
    {
        current = current->next;
    }    
    current->next = new_node;   // <- add
}

Upvotes: 4

Related Questions