Doubly Linked Lists in C Programming

Cover Image for Doubly Linked Lists in C Programming

Doubly linked lists, a fascinating data structure, provide a versatile way to manage and manipulate data. In this article, we'll delve into the world of doubly linked lists in the context of C programming. By exploring their construction and utilization through practical examples, you'll harness the power of this data structure and expand your programming toolkit.

The Allure of Data Structures

Data Structures' Appeal: Data structures enrich programming by offering efficient ways to organize and process data.

Unveiling the Essence of Doubly Linked Lists

A doubly linked list is a linear data structure where each node contains data and two pointers: one pointing to the previous node and another to the next node.

Constructing a Doubly Linked List

// Structure for Doubly Linked List Node
struct Node {
    int data;
    struct Node* prev;
    struct Node* next;
};

// Creating Doubly Linked List
struct Node* createNode(int data) {
    struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
    newNode->data = data;
    newNode->prev = NULL;
    newNode->next = NULL;
    return newNode;
}

Navigating the Doubly Linked List

// Inserting at the Beginning
void insertAtBeginning(struct Node** head, int data) {
    struct Node* newNode = createNode(data);
    newNode->next = *head;
    if (*head != NULL)
        (*head)->prev = newNode;
    *head = newNode;
}

Unveiling the Power of Doubly Linked Lists

// Traversing and Printing Doubly Linked List
void printList(struct Node* head) {
    struct Node* current = head;
    while (current != NULL) {
        printf("%d ", current->data);
        current = current->next;
    }
    printf("\n");
}

Grasping Deletion in Doubly Linked Lists

// Deleting a Node
void deleteNode(struct Node** head, struct Node* delNode) {
    if (*head == NULL || delNode == NULL)
        return;

    if (*head == delNode)
        *head = delNode->next;

    if (delNode->next != NULL)
        delNode->next->prev = delNode->prev;

    if (delNode->prev != NULL)
        delNode->prev->next = delNode->next;

    free(delNode);
}

Conclusion

Doubly linked lists add a dynamic dimension to data management in C. By immersing yourself in practical examples, you've embarked on a journey that unlocks the construction, navigation, and manipulation of doubly linked lists.

As you continue your exploration of data structures, remember that each node insertion, traversal, and deletion deepens your understanding of data organization. Keep experimenting, learning, and applying these concepts—it's through continuous practice that you elevate your programming journey!