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

1 Answer

0 votes
#include <iostream>

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

struct Node* NewNode(int data) {
    Node* node = new 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) {
        std::cout << root->data << " --> ";
        root = root->next;
    }
    std::cout << "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;

        delete dl;
    }
}

int main() {
   int arr[] = { 1, 2, 3, 4, 5, 6 };
   
   Node* root = CreateLinkedList(arr, 6);
   
   PrintLinkedList(root);
   
   DeleteLinkedList(root);
}




/*
run:

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

*/

 



answered Feb 24, 2023 by avibootz
edited Feb 24, 2023 by avibootz
...