Data Structures in C: Linked Lists

C Programming @ Freshers.in

Data structures are fundamental in computer programming, and one of the most essential data structures to master is the Linked List. In this comprehensive guide, we will delve into Linked Lists in the C programming language, providing detailed explanations, practical examples, and real data to help you grasp this crucial concept.

What is a Linked List?

A Linked List is a linear data structure that consists of a sequence of elements, where each element points to the next one in the sequence. Unlike arrays, Linked Lists do not require contiguous memory allocation, making them dynamic and efficient for insertions and deletions.

Types of Linked Lists

There are several types of Linked Lists, but the most common ones include:

  1. Singly Linked List: Each node in this list contains a data element and a reference to the next node in the sequence.
  2. Doubly Linked List: In addition to a reference to the next node, each node in this list also contains a reference to the previous node.
  3. Circular Linked List: The last node in the list points back to the first node, forming a loop.

Creating a Singly Linked List in C

Let’s start by creating a simple singly linked list in C. Here’s a code example:

#include <stdio.h>
#include <stdlib.h>
struct Node {
    int data;
    struct Node* next;
};
int main() {
    // Creating nodes
    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;
    // Traversing and printing the linked list
    struct Node* current = head;
    while (current != NULL) {
        printf("%d -> ", current->data);
        current = current->next;
    }
    return 0;
}

Output:

1 -> 2 -> 3 ->

In this example, we create a singly linked list with three nodes containing integer data. We then traverse and print the linked list to verify its structure.

Author: user