I give you an example. Note that the List structure would not really needed in this case because the first node (the head) is already the list. However a list structure could be useful in some cases, for instance to keep trace of the list length.
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int value;
struct Node * next;
} Node;
typedef struct List {
Node* head;
int length;
} List;
A function to print the list :
void printList(List *list)
{
if (!list) return;
Node * cur = list->head;
while(cur) {
printf("%d ", cur->value);
cur = cur->next;
}
printf("\n");
}
A function to free the list. Because each node is allocated separately, it must be freed separately too :
void freeList(List *list)
{
if (!list) return;
Node * cur = list->head;
while(cur) {
Node *next = cur->next;
free(cur);
cur = next;
}
free(list);
}
Node and List creation :
Node* createNode (int value)
{
Node * new = malloc((sizeof(*new)));
if (!new) return NULL;
new->value = value;
return new;
}
List* create_list(unsigned int length)
{
List* lst = malloc((sizeof(*lst)));
if (!lst) return NULL;
int value = 1;
lst->length = length;
lst->head = createNode(value++);
Node * tail = lst->head;
// Creates the wanted number of nodes giving
// a simple incremented number as its value
// Each node is linked to the next
while (--length > 0) {
Node * new = createNode(value++);
tail->next = new;
tail = new;
}
return lst;
}
int main() {
List* list = create_list(10); //Create the list with 10 nodes
printList(list); //Print it => 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
freeList(list); //Free it
return 0;
}