• Source
    1. /* Given a reference (pointer to pointer) to the head
    2.   of a list and an int, appends a new node at the end */
    3. void append(struct Node** head_ref, int new_data)
    4. {
    5. /* 1. allocate node */
    6. struct Node* new_node = (struct Node*) malloc(sizeof(struct Node));
    7.  
    8. struct Node *last = *head_ref; /* used in step 5*/
    9.  
    10. /* 2. put in the data */
    11. new_node->data = new_data;
    12.  
    13. /* 3. This new node is going to be the last node, so make next
    14.   of it as NULL*/
    15. new_node->next = NULL;
    16.  
    17. /* 4. If the Linked List is empty, then make the new node as head */
    18. if (*head_ref == NULL)
    19. {
    20. *head_ref = new_node;
    21. return;
    22. }
    23.  
    24. /* 5. Else traverse till the last node */
    25. while (last->next != NULL)
    26. last = last->next;
    27.  
    28. /* 6. Change the next of last node */
    29. last->next = new_node;
    30. return;
    31. }