Create a singly linked list and insert at the beginning and the end.
#include <stdlib.h>
typedef struct node { int val; struct node *next; } node_t;
node_t *new_node(int v)
{
node_t *n = malloc(sizeof *n);
if (n) { n->val = v; n->next = NULL; }
return n;
}
int push_front(node_t **head, int v) /* O(1) */
{
node_t *n = new_node(v);
if (!n) return -1;
n->next = *head;
*head = n;
return 0;
}
int push_back(node_t **head, int v) /* O(n); keep a tail pointer for O(1) */
{
node_t *n = new_node(v);
if (!n) return -1;
node_t **pp = head;
while (*pp) pp = &(*pp)->next; /* walk to the last next-pointer */
*pp = n;
return 0;
}
Points: pass node_t **head so the function can change the head; the pointer-to-pointer walk removes the special case for an empty list; check malloc failure; keep a tail pointer if appends are frequent. On an MCU, nodes usually come from a static pool instead of malloc.