C Programs | IT Developer
IT Developer

C Programs



Share with a Friend

Data Structures in C

Doubly Linked List - Insert Node at a Specific Position

C Program: Insert Node at a Specific Position in 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 a node at a given position

struct Node* insertAtPosition(struct Node *head, int data, int pos) {

    struct Node *newNode = createNode(data);

    struct Node *temp = head;

    int i;

 

    if (pos <= 1) {  // Insert at beginning

        newNode->next = head;

        if (head != NULL)

            head->prev = newNode;

        head = newNode;

        return head;

    }

 

    // Traverse to the position

    for (i = 1; i < pos - 1 && temp != NULL; i++)

        temp = temp->next;

 

    if (temp == NULL) {

        printf("Position out of range! Inserting at end.\n");

        return head;

    }

 

    newNode->next = temp->next;

    newNode->prev = temp;

 

    if (temp->next != NULL)

        temp->next->prev = newNode;

 

    temp->next = newNode;

 

    return head;

}

 

// Function to display the list

void displayList(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, pos, i;

 

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

    scanf("%d", &n);

 

    // Creating initial list

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

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

        scanf("%d", &data);

        head = insertAtPosition(head, data, i); // Insert at end initially

    }

 

    displayList(head);

 

    // Insert at user-defined position

    printf("\nEnter data to insert: ");

    scanf("%d", &data);

    printf("Enter position to insert: ");

    scanf("%d", &pos);

 

    head = insertAtPosition(head, data, pos);

 

    displayList(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: 10 <-> 20 <-> 30 <-> NULL

Enter data to insert: 15
Enter position to insert: 2

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

Explanation

Step

Description

1

The new node is dynamically created using malloc().

2

If position = 1, node is inserted at the beginning.

3

Else, traverse to the (pos - 1)th node.

4

Update next and prev pointers to link the new node correctly.