C Programs | IT Developer
IT Developer

C Programs



Share with a Friend

Data Structures in C

Doubly Linked List - Insert Node at the Beginning

C Program: Insert Node at the Beginning in a Doubly Linked List

C

#include <stdio.h>

#include <stdlib.h>

 

// Structure definition

struct Node {

    int data;

    struct Node *prev;

    struct Node *next;

};

 

// Function to create a new node

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;

}

 

// Function to insert at the beginning

struct Node* insertAtBeginning(struct Node *head, int data) {

    struct Node *newNode = createNode(data);

 

    if (head == NULL) {

        head = newNode;

    } else {

        newNode->next = head;

        head->prev = newNode;

        head = newNode;

    }

    return head;

}

 

// Function to display list forward

void displayForward(struct Node *head) {

    struct Node *temp = head;

    printf("\nDoubly Linked List: ");

    while (temp != NULL) {

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

        temp = temp->next;

    }

    printf("NULL\n");

}

 

int main() {

    struct Node *head = NULL;

    int n, data, i;

 

    printf("Enter number of initial nodes: ");

    scanf("%d", &n);

 

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

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

        scanf("%d", &data);

        head = insertAtBeginning(head, data);

    }

 

    displayForward(head);

    return 0;

}

Output

 
OUTPUT :

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

Doubly Linked List: 30 <-> 20 <-> 10 <-> NULL


Explanation

Step

Description

1

Define a Node with prev and next pointers.

2

Create new node dynamically using malloc().

3

Point newNode->next to the current head.

4

Update the previous link of the old head.

5

Set new node as the head.