Not tested, but the below should work. Most of the comments are straight from the wikipedia pseudocode but I added a few. I suspect that Wikipedia uses the pseudo-c so that it's more language agnostic and avoids having to deal with pointers to pointers which is not helpful if you're trying to explain the logic only
Code:
struct node
{
int data;
struct node *next;
};
// Modified from pseudo-c given at https://en.wikipedia.org/wiki/Linked_list
// Need head to be a pointer to a pointer here because if the list is empty
// we need to be able to modify head to point to the first node in the list
// (which will be created in this function)
struct node *addNode(struct node **head, int value)
{
struct node *newnode;
// allocate memory for a new node. Return NULL if it fails
newnode = malloc(sizeof (*newnode));
if (!newnode)
return NULL;
// initialise the new node
newnode->data = value; // add element's value to data part of node
newnode->next = NULL;
// append the node to the end of the list:
if (*head == NULL) { // when linked list is empty
*head = newnode; // this is why we needed a pointer to a pointer
}
else {
struct node *p;
p = *head; // assign head to p (p points to the first node in the list)
while (p->next != NULL) {
p = p->next; // traverse the list until p is the last node. The last node always points to NULL.
}
p->next = newnode; // Point the previous last node to the new node created.
}
return *head;
}
Call the function using something like:
Code:
int main(void)
{
struct node *list = NULL; // Empty list
addNode(&list, 1);
/* Create another function called, e.g. printList() */
/* Create another function called, e.g. destoryList() and call it to free the allocated memory */
return 0;
}
Edit: http://cslibrary.stanford.edu/103/LinkedListBasics.pdf see pages 13 and 14 for why a pointer to a pointer is necessary (another option is to use a dummy node)