Answer to Question #267201 in C++ for Abdirazaq korea

Question #267201

write program link list insert midle and delete ?

1
Expert's answer
2021-11-16T18:30:49-0500
#include<iostream>
using namespace std;

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


class LinkList
{
	Node* Head;
public:
	LinkList():Head(NULL){}
	void Insert(int value)
	{
		Node* NewNode = new Node(value);
		if (Head == NULL)
		{
			Head = NewNode;
		}
		else
		{
			Node* p = Head;
			while (p->next != NULL)
			{
				p = p->next;
			}
			p->next = NewNode;
		}
	}
	void InsertMid(int value)
	{
		Node* NewNode = new Node(value);
		if (Head == NULL)
		{
			Head = NewNode;
		}
		else
		{
			Node* p = Head;
			int len = 0;
			while (p != NULL)
			{
				p = p->next;
				len++;
			}
			int count = ((len % 2) == 0) ? (len / 2) : (len / 2 + 1);
			p = Head;
			while (count-- > 1)p = p->next;
			NewNode->next = p->next;
			p->next = NewNode;
		}
	}
	void Delete(int value)
	{
		if (Head == NULL)
		{
			cout << "List is empty";
		}
		else
		{
			Node* p = Head;
			if (p->data == value)
			{
				Head = p->next;
				delete p;
			}
			else
			{
				while (p->next != NULL)
				{
					if (p->next->data == value)
					{
						Node* del = p->next;
						p->next = p->next->next;
						delete del;
					}
					p = p->next;
				}
			}
		}
	}
	void DeleteMid()
	{
		if (Head == NULL)
		{
			cout << "List is empty";
		}
		else
		{
			Node* p = Head;
			int len = 0;
			while (p != NULL)
			{
				p = p->next;
				len++;
			}
			int count = ((len % 2) == 0) ? (len / 2) : (len / 2 + 1);
			p = Head;
			while (count-- > 2)p = p->next;
			Node* del = p->next;
			p->next = p->next->next;
			delete del;
		}
	}
	void Display()
	{
		Node* p = Head;
		while (p != NULL)
		{
			cout << p->data << " ";
			p = p->next;
		}
	}
};
int main()
{
	LinkList l;
	l.Insert(7);
	l.Insert(5);
	l.Insert(8);
	l.Insert(15);
	l.Insert(11);
	l.Insert(14);
	cout << "Primary list:\n";
	l.Display();
	cout << endl;
	l.InsertMid(33);
	cout << "List after InsertMid(33):\n";
	l.Display();
	cout << endl;
	l.Delete(7);
	cout << "List after Delete(7):\n";
	l.Display();
	cout << endl;
	l.Delete(8);
	cout << "List after Delete(8):\n";
	l.Display();
	cout << endl;
	l.DeleteMid();
	cout << "List after delete from midddle \n";
	l.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