Akshita gali
last year
Akshitacountry asked

Can u give C code to create nodes for a linked list?

Kelish Rai
Expert
last year
Kelish Rai answered

Here’s the C code for creating nodes in a linked list:

#include 
#include 

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

int main() {
    // Create nodes and initialize them
    Node* node1 = (Node*)malloc(sizeof(Node));
    node1->data = 11;
    node1->next = NULL;

    Node* node2 = (Node*)malloc(sizeof(Node));
    node2->data = 2;
    node2->next = NULL;

    Node* node3 = (Node*)malloc(sizeof(Node));
    node3->data = 88;
    node3->next = NULL;

    // Free allocated memory
    free(node1);
    free(node2);
    free(node3);

    return 0;
}

Here,

  • malloc() allows us to allocate memory dynamically.

  • We manually assign values to data for each node.

  • next is initialized to NULL.

  • Before using the pointers, we check if malloc() successfully allocated their memory.

  • free() is used at the end to deallocate memory and prevent memory leaks.

C++
This question was asked as part of the DSA with C++ course.