Как создать связанный список на C: пошаговое руководство с примером кода

Вот пример того, как можно создать связанный список в C:

#include <stdio.h>
#include <stdlib.h>
// Definition of a node
struct Node {
    int data;
    struct Node* next;
};
// Function to insert a new node at the beginning of the list
void insertAtBeginning(struct Node head, int data) {
    // Create a new node
    struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
    newNode->data = data;
    newNode->next = *head;
    // Update the head pointer to the new node
    *head = newNode;
}
// Function to print the linked list
void printList(struct Node* head) {
    struct Node* current = head;
    while (current != NULL) {
        printf("%d -> ", current->data);
        current = current->next;
    }
    printf("NULL\n");
}
int main() {
    // Initialize an empty linked list
    struct Node* head = NULL;
    // Insert some elements into the linked list
    insertAtBeginning(&head, 3);
    insertAtBeginning(&head, 2);
    insertAtBeginning(&head, 1);
    // Print the linked list
    printf("Linked List: ");
    printList(head);
    return 0;
}

Этот код создает простой связанный список с тремя узлами, содержащими целочисленные данные. Функция insertAtBeginningвставляет новый узел в начало списка, а функция printListпечатает элементы связанного списка.