Answer to Question #265843 in C++ for Ahmed Ali

Question #265843

Implement the code of Doubly Linked List.



Add your roll # node using Append function.


Add the last two digits of your contact # using Prepend function


Add your favorite digit between roll # and contact #.


And display the doubly linked list.



1
Expert's answer
2021-11-15T00:23:12-0500
#include <bits/stdc++.h>
using namespace std;


class Node
{
	public:
    	int d;
    	Node* nxt;
    	Node* prev;
};
void push(Node** h_ref, int n_data)
{
	Node* n_node = new Node();
	n_node->d = n_data;
	n_node->nxt = (*h_ref);
	n_node->prev = NULL;
	if ((*h_ref) != NULL)
		(*h_ref)->prev = n_node;
	(*h_ref) = n_node;
}
void insert(Node* pv_node, int n_data)
{
	if (pv_node == NULL)
	{
		cout<<"the given previous node cannot be NULL";
		return;
	}
	Node* n_node = new Node();
	n_node->d = n_data;
	n_node->nxt = pv_node->nxt;
	pv_node->nxt = n_node;
	n_node->prev = pv_node;
	if (n_node->nxt != NULL)
		n_node->nxt->prev = n_node;
}
void append(Node** h_ref, int n_data)
{
	Node* n_node = new Node();
	Node* last = *h_ref; 
	n_node->d = n_data;
	n_node->nxt = NULL;
	if (*h_ref == NULL)
	{
		n_node->prev = NULL;
		*h_ref = n_node;
		return;
	}
	while (last->nxt != NULL)
		last = last->nxt;
	last->nxt = n_node;
	n_node->prev = last;


	return;
}
void display(Node* node)
{
	Node* last;
	cout<<"\nTraversal in forward direction \n";
	while (node != NULL)
	{
		cout<<" "<<node->d<<" ";
		last = node;
		node = node->nxt;
	}


	cout<<"\nTraversal in reverse direction \n";
	while (last != NULL)
	{
		cout<<" "<<last->d<<" ";
		last = last->prev;
	}
}


int main()
{
	Node* h = NULL;
	append(&h, 1);
	push(&h, 2);
	push(&h, 3);
	append(&h, 4);
	insert(h->nxt, 5);


	cout << "Created DLL is: ";
	display(h);


	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