Answer to Question #270728 in C++ for Roe

Question #270728

Note: No global declarations


Call the functions in main through menu



Implement the following :


Singly Linked List with following functions :


1)insert_at_head(node* & head, int val);


2)insert_at_tail(node* & head, int val);


3)display(node* head) ;


4)insert_at_pos(node* & head, int val,int pos);


5)delete_at_head(node* & head);


6)delete_at_tail(node* & head);


7)delete_at_pos(node* & head, int pos);

1
Expert's answer
2021-11-24T00:40:47-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