Thursday, 29 October 2026

.Insert a node at the end of a doubly linked list

 #include <iostream>

using namespace std;

struct Node

{

    int data;

    Node* prev;

    Node* next;

};


int main()

{

    Node* head = NULL;

    Node* temp;

    Node* newNode;


    // Create first node

    head = new Node;

    head->data = 10;

    head->prev = NULL;

    head->next = NULL;


    // Create second node

    temp = new Node;

    temp->data = 20;

    temp->prev = head;

    temp->next = NULL;

    head->next = temp;




  // Insert new node at the end

    newNode = new Node;

    newNode->data = 30;

    newNode->next = NULL;

    newNode->prev = temp;

    temp->next = newNode;


    // Display the list

    temp = head;


    cout << "Doubly Linked List: ";


    while (temp != NULL)

    {

        cout << temp->data << " ";

        temp = temp->next;

    }


    return 0;

}

head->next = temp; connects node 10 to node 20.

temp->next = newNode; connects node 20 to node 30.

newNode->prev = temp; connects node 30 backward to node 20.


  • First, create nodes containing 10 and 20.

  • Create a new node containing 30.

  • temp->next = newNode connects node 20 to node 30.

  • newNode->prev = temp connects node 30 back to node 20.

  • Finally, display all nodes using the next pointer.

Remember: prev points backward, and next points forward.