Code Sharing: Simplest Linked List Template in C Language

// Simple linked list example, but without freeing memory
#include <stdio.h>
#include <stdlib.h> // For malloc memory allocation
// Define a type as a structure pointer, which has a member that is a pointer to another structure of the same type, forming a linked structure called a linked list
typedef struct node {
    int number;
    struct node *next; // Pointer to a structure of the same type
} node;

int main() {
    // Create three nodes
    node* node1 = (node*)malloc(sizeof(node));
    node* node2 = (node*)malloc(sizeof(node));
    node* node3 = (node*)malloc(sizeof(node));
    // Store three numbers in the nodes using three different assignment methods
    node1->number = 1;
    node1->next = node2;
    *node2 = (node){2, node3}; // Must not omit member variables in order
    *node3 = (node){.number=3, .next=NULL}; // Can omit a member variable but not in order

    // Traverse the linked list and print the nodes
    node* current = node1;
    while(current != NULL) {
        if(current == node2) {
            current->number = 4;  // Modify
            printf("%d", node2->number);
        }
        printf("%d\n", current->number);
        current = current->next;
    }
    // Memory is not freed here, for learning purposes only
    return 0;
}

Leave a Comment