C Programs | IT Developer
IT Developer

C Programs



Share with a Friend

Data Structures in C

Doubly linked list creation

C Program: Create a Doubly Linked List

C

#include <stdio.h>

#include <stdlib.h>

 

// Structure for a doubly linked list node

struct Node {

    int data;

    struct Node *prev;

    struct Node *next;

};

 

// Function to create a doubly linked list

struct Node* createDoublyList(int n) {

    struct Node *head = NULL, *temp = NULL, *newNode = NULL;

    int data, i;

 

    if (n <= 0) {

        printf("Invalid number of nodes.\n");

        return NULL;

    }

 

    for (i = 1; i <= n; i++) {

        newNode = (struct Node*)malloc(sizeof(struct Node));

        if (newNode == NULL) {

            printf("Memory allocation failed!\n");

            exit(0);

        }

 

        printf("Enter data for node %d: ", i);

        scanf("%d", &data);

 

        newNode->data = data;

        newNode->prev = NULL;

        newNode->next = NULL;

 

        if (head == NULL) {

            head = newNode;

        } else {

            temp->next = newNode;

            newNode->prev = temp;

        }

 

        temp = newNode;

    }

 

    return head;

}

 

// Function to display the list forward

void displayForward(struct Node *head) {

    struct Node *temp = head;

    printf("\nDoubly Linked List (Forward): ");

    while (temp != NULL) {

        printf("%d <-> ", temp->data);

        temp = temp->next;

    }

    printf("NULL\n");

}

 

// Function to display the list in reverse order

void displayBackward(struct Node *head) {

    struct Node *temp = head;

    if (head == NULL) {

        printf("\nList is empty.\n");

        return;

    }

 

    // Move to last node

    while (temp->next != NULL) {

        temp = temp->next;

    }

 

    printf("\nDoubly Linked List (Backward): ");

    while (temp != NULL) {

        printf("%d <-> ", temp->data);

        temp = temp->prev;

    }

    printf("NULL\n");

}

 

int main() {

    struct Node *head = NULL;

    int n;

 

    printf("Enter number of nodes: ");

    scanf("%d", &n);

 

    head = createDoublyList(n);

 

    displayForward(head);

    displayBackward(head);

 

    return 0;

}

Output

 
OUTPUT :

Enter number of nodes: 4
Enter data for node 1: 10
Enter data for node 2: 20
Enter data for node 3: 30
Enter data for node 4: 40

Doubly Linked List (Forward): 10 <-> 20 <-> 30 <-> 40 <-> NULL
Doubly Linked List (Backward): 40 <-> 30 <-> 20 <-> 10 <-> NULL

Explanation

Step

Description

1

Define a Node with data, prev, and next pointers.

2

Dynamically create each node using malloc().

3

Update prev and next links properly.

4

Print the list forward and backward.