Answer to Question #272779 in C++ for Tarurendra Kushwah

Question #272779
  1. Write a menu driven program that maintains a singly linked list and implements the following operations (using separate functions):
  2. Delete an existing element after a specific location
  3. Display all the elements
1
Expert's answer
2021-11-28T18:41:31-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 Delete(int loc)
	{
		if (Head == NULL)
		{
			cout << "List is empty";
		}
		else if (loc == 0)
		{
			Node* del = Head;
			Head = del->next;
			delete del;
		}
		else
		{
			Node* p = Head;
			Node* prev= Head;
			while (p!= NULL&&loc!=0)
			{
				prev = p;
				p = p->next;
				loc--;
			}
			if (loc != 0)
			{
				cout << "Incorrect element position!";
			}
			else
			{
				prev->next = p->next;
				delete p;
			}
		}
	}
	
	void Display()
	{
		cout << "\nElements of list are ";
		Node* p = Head;
		while (p != NULL)
		{
			cout << p->data << " ";
			p = p->next;
		}
	}
};


void MENU()
{
	cout << "\nPlease, choose one of the following:\n";
	cout << "A - add new node to list\n"
		<< "D - delete element from list after some position\n"
		<< "S - show all elements of list\n"
		<< "E - exit program\n";
	cout << "Your choice: ";
}
int main()
{
	LinkList l;
	char c;
	do
	{
		MENU();
		cin >> c;
		switch (c)
		{
		case 'a':case 'A':
		{
			int value;
			cout << "Please, enter a value to add: ";
			cin >> value;
			l.Insert(value);
			break;
		}
		case 'd':case 'D':
		{
			int loc;
			cout << "Please, enter a specific location of element: ";
			cin >> loc;
			l.Delete(loc);
			break;
		}
		case 's':case 'S':
		{
			l.Display();
			break;
		}
		}
		
	} while (c!='e'&&c!='E');
}

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