Answer to Question #238002 in C++ for Myname

Question #238002
Write a program to implement the Doubly linked list. Perform the following operations on
the doubly linked list:
 Creating an empty doubly linked list
 Adding the new element at the beginning of the linked list.
 Deletion of a node after a particular location.
 Counting the no of nodes.
 Displaying the linked list.
1
Expert's answer
2021-09-16T13:01:35-0400


#include <iostream>
using namespace std;


struct DoublyList{
    int item;
    
    struct DoublyList* nextNode;
    struct DoublyList* prevNode;
};
 


void addAtBeginning(struct DoublyList** head, int data)
{
    struct DoublyList* newNode = (struct DoublyList*)malloc(sizeof(struct DoublyList));
 
    newNode->item = data;
 
    newNode->nextNode = (*head);
    newNode->prevNode = NULL;
 
    if ((*head) != NULL)
        (*head)->prevNode = newNode;
 
    (*head) = newNode;
    
}
//Creating Empty linked list
void EmptyLinkedList(struct DoublyList* node){
	node->nextNode = NULL;
	node->prevNode = NULL;
}
 //Counting the number of nodes
int countNodes(struct DoublyList* node){
	int i = 0;
	while(node!=NULL){
		i++;
		node = node->nextNode;
	}
	return i;
}
//Deleting nodes after a particular location
void deleteNodeAtLocation(DoublyList** head, DoublyList* node)
{
   
    if (*head == NULL || node == NULL)
        return;
 
    
    if (*head == node)
        *head = node->nextNode;
 
    
    if (node->nextNode != NULL)
        node->nextNode->prevNode = node->prevNode;
 
    
    if (node->prevNode != NULL)
        node->prevNode->nextNode = node->nextNode;
 
    
    free(node);
    return;
}
void displayList(struct DoublyList* head)
{
    struct DoublyList* lastNode;
    cout <<"\nDisplaying from the beggining \n";
    while (head != NULL) {
        cout <<"  "<< head->item;
        lastNode = head;
        
        head = head->nextNode;
        
    }
 
    cout <<"\nDisplaying from the end \n";
    while (lastNode != NULL) {
        cout <<"  "<< lastNode->item;
        
        lastNode = lastNode->prevNode;
        
    }
}
 


int main()
{
    
    struct DoublyList* list = NULL;
    addAtBeginning(&list, 20);
 
    addAtBeginning(&list, 30);
 
    addAtBeginning(&list, 40);
 
    
    displayList(list);
  cout<<"\nThe number of nodes:  "<<countNodes(list)<<endl;
    getchar();
    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