Welcome to the exciting world of C programming! Today, we'll be diving into Linked Lists, a fundamental data structure used in many real-world applications. Let's get started! 📝
A Linked List is a collection of nodes, where each node contains data and a reference (link) to the next node in the sequence. This structure allows for dynamic memory allocation, making it ideal for handling dynamic data sets.
Each node in a Linked List typically consists of:
Let's create a simple Linked List using C:
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node* next;
} Node;
Node* createNode(int data) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = data;
newNode->next = NULL;
return newNode;
}
void append(Node** head, int data) {
Node* newNode = createNode(data);
if (*head == NULL) {
*head = newNode;
return;
}
Node* current = *head;
while (current->next != NULL) {
current = current->next;
}
current->next = newNode;
}
void printList(Node* head) {
Node* current = head;
while (current != NULL) {
printf("%d -> ", current->data);
current = current->next;
}
printf("NULL\n");
}
int main() {
Node* head = NULL;
append(&head, 10);
append(&head, 20);
append(&head, 30);
printf("Linked List: ");
printList(head);
return 0;
}In this example, we create a Node structure, define functions to create a new node (createNode), append a new node to the end of the list (append), and print the Linked List (printList). The main function demonstrates how to use these functions to create a simple Linked List with nodes containing integers.
Which C header file is required to use `malloc` function?
Remember, practice makes perfect! Experiment with different data types and Linked List implementations to solidify your understanding of this powerful data structure. Happy coding! 💡