#include <stdio.h>
#include <stdlib.h>

typedef struct Node {
    int data;
    struct Node *next;
} node;

// Function to convert array to linked list
node* convertToLL(int arr[], int sz) {
    if (sz == 0) return NULL; // Edge case: empty array

    // Create the head node
    node *head = (node *)malloc(sizeof(node));
    head->data = arr[0];
    head->next = NULL;

    // Keep track of the current node
    node *current = head;

    // Loop through the array to create and link nodes
    for (int i = 1; i < sz; i++) {
        node *newNode = (node *)malloc(sizeof(node));
        newNode->data = arr[i];
        newNode->next = NULL;
        current->next = newNode; // Link the new node to the current node
        current = newNode;       // Move to the new node
    }

    return head; // Return the head of the linked list
}

// Function to print the linked list
void printLinkedList(node *head) {
    node *current = head;
    while (current != NULL) {
        printf("%d -> ", current->data);
        current = current->next;
    }
    printf("NULL\n");
}

// Main function
int main() {
    int sz = 5;
    int *arr = (int *)malloc(sz * sizeof(int)); // Allocate memory for the array

    printf("Enter %d integers:\n", sz);
    for (int i = 0; i < sz; i++) {
        scanf("%d", &arr[i]);
    }

    // Convert array to linked list
    node *head = convertToLL(arr, sz);

    // Print the linked list
    printf("Linked List: ");
    printLinkedList(head);

    // Free the allocated memory for the array
    free(arr);

    // Free the allocated memory for the linked list
    node *current = head;
    while (current != NULL) {
        node *temp = current;
        current = current->next;
        free(temp);
    }

    return 0;
}

Embed on website

To embed this program on your website, copy the following code and paste it into your website's HTML: