How to create a singly linked list from a given array in C

1 Answer

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

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

struct Node* NewNode(int data) {
    Node* node = malloc(sizeof(Node));
    
    node->data = data;
    node->next = NULL;

    return node;
}

void AddNewNode(Node** root, int data) {
    Node* node = NewNode(data);
    Node* ptr;
    if (*root == NULL) {
        *root = node;
    }
    else {
        ptr = *root;
        while (ptr->next != NULL) {
            ptr = ptr->next;
        }
        ptr->next = node;
    }
}

void PrintLinkedList(Node* root) {
    while (root != NULL) {
        printf("%d --> ", root->data);
        root = root->next;
    }
    puts("NULL");
}

Node* CreateLinkedList(int arr[], int size) {
    Node* root = NULL;

    for (int i = 0; i < size; i++) {
        AddNewNode(&root, arr[i]);
    }

    return root;
}

void DeleteLinkedList(Node* root) {
    Node* tmp = root;

    while (tmp != NULL) {
        Node* dl = tmp;
        tmp = tmp->next;
     
        free(dl);
    }
}

int main(void) {
    int arr[] = { 1, 2, 3, 4, 5, 6 };

    Node* root = CreateLinkedList(arr, 6);

    PrintLinkedList(root);

    DeleteLinkedList(root);

    return 0;
}




/*
run:

1 --> 2 --> 3 --> 4 --> 5 --> 6 --> NULL

*/

 



answered Feb 24, 2023 by avibootz

Related questions

...