Answer to Question #289034 in C++ for Olivia

Question #289034

Note:


Only diagram needed no code



TASK:


Head->5->3 - >7 - >9 - >1 - >Null


Draw a diagram of the above list after the following lines of code have been executed:


Node * prev = head ->next;


Node* nodeToInsert = new Node;


nodeToInsert-> data = 4;


nodeToInsert -> next = prev -> next;


prev -> next = nodeToInsert;

1
Expert's answer
2022-01-20T08:28:12-0500
#include<iostream>
using namespace std;

struct Node
{
	int data;
	struct Node *prev;
	struct Node *next;
	Node(int _data) :data(_data), prev(NULL), next(NULL) {}
	Node(){}
};

class DLL
{
public:
	Node *Head;
	Node *Tail;
	DLL() :Head(NULL), Tail(NULL) {}
	void Insert(int value)
	{
		struct Node *p = new Node(value);
		if (Head != 0)
		{
			p->prev = Tail;
			Tail->next = p;
			Tail = p;
		}
		else
		{
			p->prev = NULL;
			Head = Tail = p;
		}
	}
	void Display()
	{
		struct Node *p = Head;
		cout<<"\nHead->";
		while (p!=NULL)
		{
			cout << p->data << "->";
			p = p->next;
		}
		cout<<"Null";
	}
};

int main()
{
	DLL d;
	d.Insert(5);
	d.Insert(3);
	d.Insert(7);
	d.Insert(9);
	d.Insert(1);
	d.Display();
	Node* prev=d.Head->next;//prev is pointer on Node(3)
	Node* nodeToInsert=new Node;//Creating new Node
	nodeToInsert->data=4;//Assign value 4 of new Node 
	nodeToInsert->next=prev->next;//new Node->next is pointer on Node(7) 
	prev->next=nodeToInsert;//new Node of value 4 is Node after Node(3) and before Node(7)
	d.Display();//Head->5->3->4->7->9->1->Null
}

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