C Doubly Linked List 🎯

beginner
10 min

C Doubly Linked List 🎯

Welcome to our deep dive into C Doubly Linked Lists! This guide is designed to help both beginners and intermediates understand this essential data structure. Let's embark on this journey together! 🚀

What is a Doubly Linked List? 📝

A Doubly Linked List is a linear data structure that uses pointers to link elements together in a chain. Unlike a Singly Linked List, each node in a Doubly Linked List contains two pointers: one pointing to the next node (just like in a Singly Linked List) and another pointing to the previous node.

Why Doubly Linked List? 💡

Doubly Linked Lists offer several advantages over Singly Linked Lists. They allow for efficient traversal in both directions and can be useful in situations where we need to iterate through a list from the end (e.g., in reverse order).

Node Structure 📝

A node in a Doubly Linked List contains three parts:

  1. Data: The value stored in the node.
  2. Next Pointer: A pointer pointing to the next node in the list.
  3. Previous Pointer: A pointer pointing to the previous node in the list.

Here's a simple representation of a Doubly Linked List node:

c
struct Node { int data; struct Node* next; struct Node* prev; };

Creating a Doubly Linked List 📝

Creating a Doubly Linked List involves several steps:

  1. Defining the Node structure.
  2. Allocating memory for the first node (head) and initializing it.
  3. Adding new nodes to the end of the list.
  4. Adding new nodes to the beginning of the list.
  5. Deleting nodes from the list.

Example 1: Creating a Doubly Linked List 📝

Let's create a simple Doubly Linked List with three nodes: 5, 10, and 15.

c
#include <stdio.h> #include <stdlib.h> struct Node { int data; struct Node* next; struct Node* prev; }; void addNodeAtEnd(struct Node**, int data); void addNodeAtBeginning(struct Node**, int data); void displayList(struct Node*); int main() { struct Node *head = NULL; addNodeAtBeginning(&head, 5); addNodeAtEnd(head, 10); addNodeAtEnd(head, 15); printf("Doubly Linked List: "); displayList(head); return 0; } // Implementation of addNodeAtBeginning, addNodeAtEnd, and displayList functions here

Example 2: Deleting a Node 📝

Let's delete the node with the data 10 from our Doubly Linked List.

c
// Implementation of deleteNode function here int main() { // ... (same as before) deleteNode(head, 10); printf("Doubly Linked List after deleting node with data 10: "); displayList(head); return 0; }

Quiz 📝

Quick Quiz
Question 1 of 1

What is the main advantage of a Doubly Linked List over a Singly Linked List?

Keep learning and happy coding! 🎉🎓