Answer to Question #249808 in C++ for Dunag

Question #249808
Write a c++ program performing deletion, insertion and display as doubly linked list
1
Expert's answer
2021-10-12T00:36:45-0400
#include <iostream>
using namespace std;
struct Node {
   int data;
   struct Node* next;
   struct Node* prev;
};
  
void insertAtBeggining(struct Node** head, int newD)
{
   struct Node* newNode = new Node;
   newNode->data = newD;
   newNode->next = (*head);
   newNode->prev = NULL;
   if ((*head) != NULL)
   (*head)->prev = newNode;
   (*head) = newNode;
}


void insertAfter(struct Node* prevN, int newD)
{
   if (prevN == NULL) {
   cout<<"Previous node cannot be NULL";
   return;
}
   struct Node* newNode = new Node;
   newNode->data = newD;
   newNode->next = prevN->next;
   prevN->next = newNode;
   newNode->prev = prevN;
   if (newNode->next != NULL)
   newNode->next->prev = newNode;
}
  
void insertAtEnd(struct Node** head, int newD)
{
   struct Node* newNode = new Node;
  
   struct Node* L = *head; 
   newNode->data = newD;
   newNode->next = NULL;
   if (*head == NULL) {
   newNode->prev = NULL;
   *head = newNode;
    return;
}
while (L->next != NULL)
L = L->next;
L->next = newNode;
newNode->prev = L;
return;
}
void displayList(struct Node* node) {
   struct Node* L;
  
   while (node != NULL) {
      cout<<node->data<<"<==>";
      L = node;
      node = node->next;
   }
   if(node == NULL)
   cout<<"NULL";
   }


int main() {
   struct Node* head = NULL;
   insertAtEnd(&head, 4);
   insertAtBeggining(&head, 2);
   insertAtBeggining(&head, 1);
   insertAtEnd(&head, 5);
   insertAfter(head->next, 3);
  
   cout<<"Doubly linked list: "<<endl;
   displayList(head);
   return 0;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS