Вставка элемента в определенную позицию в списке на C: объяснение двух методов

Вот пример полной программы на языке C, которая вставляет элемент в n-ю позицию списка. Я предлагаю два метода выполнения этой задачи.

Метод 1: использование массивов

#include <stdio.h>
#define MAX_SIZE 100
void insertElement(int list[], int size, int element, int position) {
    if (position < 0 || position > size) {
        printf("Invalid position!\n");
        return;
    }
// Shift elements to the right
    for (int i = size - 1; i >= position; i--) {
        list[i + 1] = list[i];
    }
// Insert the element at the given position
    list[position] = element;
    printf("Element inserted successfully!\n");
    // Print the updated list
    printf("Updated List: ");
    for (int i = 0; i <= size; i++) {
        printf("%d ", list[i]);
    }
}
int main() {
    int list[MAX_SIZE];
    int size, element, position;
    printf("Enter the size of the list: ");
    scanf("%d", &size);
    printf("Enter the elements of the list: ");
    for (int i = 0; i < size; i++) {
        scanf("%d", &list[i]);
    }
    printf("Enter the element to be inserted: ");
    scanf("%d", &element);
    printf("Enter the position to insert the element: ");
    scanf("%d", &position);
    insertElement(list, size, element, position);
    return 0;
}

Метод 2: использование связанного списка

#include <stdio.h>
#include <stdlib.h>
struct Node {
    int data;
    struct Node* next;
};
void insertElement(struct Node head, int element, int position) {
    struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
    newNode->data = element;
    newNode->next = NULL;
    if (position == 1) {
        newNode->next = *head;
        *head = newNode;
        printf("Element inserted successfully!\n");
        return;
    }
    struct Node* temp = *head;
    for (int i = 1; i < position - 1; i++) {
        if (temp == NULL) {
            printf("Invalid position!\n");
            return;
        }
        temp = temp->next;
    }
    if (temp == NULL) {
        printf("Invalid position!\n");
        return;
    }
    newNode->next = temp->next;
    temp->next = newNode;
    printf("Element inserted successfully!\n");
}
void printList(struct Node* head) {
    printf("Updated List: ");
    while (head != NULL) {
        printf("%d ", head->data);
        head = head->next;
    }
}
int main() {
    struct Node* head = NULL;
    int element, position;
    printf("Enter the element to be inserted: ");
    scanf("%d", &element);
    printf("Enter the position to insert the element: ");
    scanf("%d", &position);
    insertElement(&head, element, position);
    printList(head);
    return 0;
}