C Programs | IT Developer
IT Developer

C Programs



Share with a Friend

Data Structures in C

Doubly Linked List - Insert Node at the End

C Program: Insert Node at the End 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 a node at the end

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

    struct Node *newNode = createNode(data);

    struct Node *temp = head;

 

    if (head == NULL) {

        head = newNode;

        return head;

    }

 

    // Traverse to the last node

    while (temp->next != NULL)

        temp = temp->next;

 

    // Link new node

    temp->next = newNode;

    newNode->prev = temp;

 

    return head;

}

 

// Function to display the 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 nodes to insert at end: ");

    scanf("%d", &n);

 

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

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

        scanf("%d", &data);

        head = insertAtEnd(head, data);

    }

 

    displayForward(head);

    return 0;

}

Output

 
OUTPUT :
Enter number of nodes to insert at end: 3
Enter data for node 1: 5
Enter data for node 2: 10
Enter data for node 3: 15

Doubly Linked List: 5 <-> 10 <-> 15 <-> NULL

Explanation

Step

Description

1

A new node is dynamically created using malloc().

2

If the list is empty, new node becomes the head.

3

Otherwise, traverse to the last node using while (temp->next != NULL).

4

Update links so that the last node points to the new node.