C Linked List Introduction 🎯

beginner
19 min

C Linked List Introduction 🎯

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! 📝

What is a Linked List? 💡

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.

Node Structure 📝

Each node in a Linked List typically consists of:

  1. Data: The actual value stored in the node.
  2. Next Pointer: A pointer that points to the next node in the sequence.

Creating a Linked List 🎯

Let's create a simple Linked List using C:

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.

Quiz 📝

Quick Quiz
Question 1 of 1

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! 💡