Answer to Question #324368 in C++ for yilak47

Question #324368

Write a C++ program which performs the following two operations on doubly linked list



 Insertion of a new element at any mentioned position in the list.



 Deletion of an element which contains the given key



 Deletion of an element which found at the given position.

1
Expert's answer
2022-04-06T02:27:40-0400
#include <iostream>

using namespace std;


#include<iostream>
#include<algorithm>
using namespace std;

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


class DLL
{


	Node *Head;
	Node *Tail;
	int sizeList;
public:
	DLL() :Head(NULL), Tail(NULL), sizeList(0) {}
	void Insert(int value, int pos)
	{
		struct Node *p = new Node(value);
		if (pos >= sizeList)
		{
			if (Head != 0)
			{
				p->prev = Tail;
				Tail->next = p;
				Tail = p;
			}
			else
			{
				p->prev = NULL;
				Head = Tail = p;
			}
		}
		else
		{
			int i = 1;
			struct Node *t = Head;
			while (i != pos)
			{
				i++;
				t = t->next;
			}
			p->next = t->next;
			t->next->prev = p;
			t->next = p;
		}
		sizeList++;
	}
	void Delete(int pos)
	{
		if (pos >= sizeList||pos==1)
		{
			struct Node *p = Tail;
			Tail = p->prev;
			delete p;
		}
		else
		{
			int i = 1;
			struct Node *p = Head;
			while (i != pos)
			{
				i++;
				p = p->next;
			}
			p->prev->next = p->next;
			p->next->prev = p->prev;
			delete p;
		}
		sizeList--;
	}
	void DeleteVal(int value)
	{
		if (value == Head->data)
		{
			struct Node *p = Head;
			Head = Head->next;
			delete p;
		}
		else
		{
			int i = 1;
			struct Node *p = Head;
			while (i != sizeList)
			{
				i++;
				if (p->data == value)
				{
					p->prev->next = p->next;
					p->next->prev = p->prev;
					delete p;
					break;
				}
				p = p->next;
				
			}
			
		}
		sizeList--;
	}
	void Display()
	{
		struct Node *p = Head;
		int i = 0;
		while (i<sizeList)
		{
			cout << p->data << " ";
			p = p->next;
			i++;
		}
	}
	
};


int main()
{
	DLL dl;
	dl.Insert(5, 1);
	dl.Insert(1, 2);
	dl.Insert(3, 3);
	dl.Insert(7, 4);
	dl.Insert(8, 5);
	cout << "Primary List:";
	dl.Display();
	dl.Delete(2);
	cout << "\nDelete from position 2:";
	dl.Display();
	dl.DeleteVal(7);
	cout << "\nDelete value 7:";
	dl.Display();
}

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