#include <stdio.h>
#include <stdlib.h>
/* -----------------------------
Definition of a singly linked list node
----------------------------- */
typedef struct Node {
int value; // Data stored in the node
struct Node *next; // Pointer to the next node
} Node;
/* -----------------------------
Create a new node with a given value
Returns: pointer to the new node, or NULL on failure
----------------------------- */
Node *node_create(int value) {
Node *n = malloc(sizeof(*n));
if (!n) {
fprintf(stderr, "Memory allocation failed\n");
return NULL;
}
n->value = value;
n->next = NULL;
return n;
}
/* -----------------------------
Insert a new value at the front of the list
head: pointer to the head pointer (so we can modify it)
----------------------------- */
void list_push_front(Node **head, int value) {
Node *n = node_create(value);
if (!n) return;
n->next = *head; // New node points to old head
*head = n; // Head now points to new node
}
/* -----------------------------
Insert a new value at the end of the list
----------------------------- */
void list_push_back(Node **head, int value) {
Node *n = node_create(value);
if (!n) return;
// If the list is empty, new node becomes the head
if (*head == NULL) {
*head = n;
return;
}
// Otherwise, walk to the last node
Node *cur = *head;
while (cur->next != NULL)
cur = cur->next;
cur->next = n; // Attach new node at the end
}
/* -----------------------------
Print all values in the list
----------------------------- */
void list_print(const Node *head) {
printf("List: ");
for (const Node *cur = head; cur != NULL; cur = cur->next)
printf("%d ", cur->value);
printf("\n");
}
/* -----------------------------
Free all nodes in the list
----------------------------- */
void list_free(Node *head) {
while (head) {
Node *next = head->next; // Save next pointer
free(head); // Free current node
head = next; // Move to next
}
}
/* -----------------------------
Demonstration of list usage
----------------------------- */
int main(void) {
Node *head = NULL; // Start with an empty list
// Insert elements
list_push_front(&head, 3);
list_push_front(&head, 2);
list_push_front(&head, 1);
list_push_back(&head, 5);
list_push_back(&head, 4);
// Print the list
list_print(head);
// Free memory
list_free(head);
return 0;
}
/*
run:
List: 1 2 3 5 4
*/