c++ doubly linked list

A doubly linked list is a data structure where each node contains a reference to the previous and next nodes in the list. Here are the steps to implement a doubly linked list in C++:

  1. Define the structure for the doubly linked list node:
struct Node {
   int data;
   Node* prev;
   Node* next;
};
  1. Create the necessary functions to manipulate the doubly linked list. Some common functions include:

  2. Creating a new node: c++ Node* createNode(int data) { Node* newNode = new Node(); newNode->data = data; newNode->prev = NULL; newNode->next = NULL; return newNode; }

  3. Inserting a node at the beginning of the list: c++ void insertAtBeginning(Node head, int data) { Node* newNode = createNode(data); if (*head == NULL) { *head = newNode; } else { newNode->next = *head; (*head)->prev = newNode; *head = newNode; } }

  4. Inserting a node at the end of the list: c++ void insertAtEnd(Node head, int data) { Node* newNode = createNode(data); if (*head == NULL) { *head = newNode; } else { Node temp = head; while (temp->next != NULL) { temp = temp->next; } temp->next = newNode; newNode->prev = temp; } }

  5. Deleting a node from the list: c++ void deleteNode(Node head, Node* delNode) { if (*head == NULL || delNode == NULL) { return; } if (*head == delNode) { *head = delNode->next; } if (delNode->next != NULL) { delNode->next->prev = delNode->prev; } if (delNode->prev != NULL) { delNode->prev->next = delNode->next; } delete delNode; }

  6. Displaying the contents of the list: c++ void displayList(Node* head) { Node* temp = head; while (temp != NULL) { cout << temp->data << " "; temp = temp->next; } cout << endl; }

  7. Test the doubly linked list by calling the functions as needed:

int main() {
   Node* head = NULL;
   insertAtBeginning(&head, 1);
   insertAtEnd(&head, 2);
   insertAtEnd(&head, 3);
   displayList(head);
   deleteNode(&head, head);
   displayList(head);
   return 0;
}

By following these steps, you can create and manipulate a doubly linked list in C++.