Linked Lists in C
Linked lists are data structures that consist of nodes, where each node contains a value and a pointer to the next node. They are useful for dynamically storing and manipulating data.
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* next;
};
void printList(struct Node* head) {
struct Node* current = head;
while (current != NULL) {
printf("%d ", current->data);
current = current->next;
}
printf("\n");
}
int main() {
struct Node* head = NULL;
struct Node* second = NULL;
struct Node* third = NULL;
// Allocate memory for nodes
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);
// Free allocated memory
free(head);
free(second);
free(third);
return 0;
}
In this example, a simple linked list is created with three nodes. The printList function traverses the linked list and prints the data in each node.
No comments:
Post a Comment