link list
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* next;
};
void printList(struct Node* n) {
while (n != NULL) {
printf("%d ", n->data);
n = n->next;
}
printf("\n");
}
int main() {
struct Node* head = NULL;
struct Node* second = NULL;
struct Node* third = NULL;
head = (struct Node*)malloc(sizeof(struct Node));
second = (struct Node*)malloc(sizeof(struct Node));
third = (struct Node*)malloc(sizeof(struct Node));
head->data = 1;
head->next = second;
second->data = 2;
second->next = third;
third->data = 3;
third->next = NULL;
printList(head);
return 0;
}
Explanation:
- The code includes necessary header files: <stdio.h>
for input/output and <stdlib.h>
for dynamic memory allocation.
- struct Node
defines a node structure for a singly linked list containing an integer data
field and a pointer next
to the next node.
- printList
function prints the elements of the linked list by traversing it using a while loop.
- In main()
function:
- Three pointers of type struct Node
are declared: head
, second
, and third
, all initialized to NULL
.
- Memory is allocated for each node using malloc
to create space in the heap for the nodes.
- Data is assigned to each node's data
field: head->data = 1
, second->data = 2
, third->data = 3
.
- Pointers are assigned to establish the links between nodes: head->next = second
, second->next = third
, third->next = NULL
.
- printList(head)
is called to print the linked list starting from the head
node.
- Finally, return 0;
signifies successful completion of the program.