c make 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;
}
}
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:
1. Include Headers: stdio.h
for standard input/output operations and stdlib.h
for memory allocation functions.
2. Node Structure Definition: Defines a structure Node
containing an integer data
and a pointer next
to another Node
.
3. printList Function: Prints the data in the linked list starting from a given node, iterating through the list using a while
loop until the end is reached (NULL
).
4. Main Function:
- Declares three pointers to Node
as head
, second
, and third
, initially pointing to NULL
.
- Allocates memory for three nodes using malloc
.
- Assigns values to data
and next
pointers of each node to create a linked list with values 1 -> 2 -> 3 -> NULL
.
- Calls printList
function to print the linked list starting from the head
node.