Akshita
asked

Expert
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
datafor each node.nextis initialized toNULL.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.
Our Experts
Sudip BhandariHead of Growth/Marketing
Apekchhya ShresthaSenior Product Manager
Kelish RaiTechnical Content Writer
Abhilekh GautamSystem Engineer
Palistha SinghTechnical Content Writer
Sarthak BaralSenior Content Editor
Saujanya Poudel
Abhay Jajodia
Nisha SharmaTechnical Content Writer
Udayan ShakyaTechnical Content Writer