Write in C++ please. I\'m using a VirtualBox machine running linux using Geany a
ID: 3815516 • Letter: W
Question
Write in C++ please. I'm using a VirtualBox machine running linux using Geany as an editor.
The goal of this assignment is to get some experience with pointers and dynamic memory by implementing a simple linked list. Background: A set is a collection, in which any object may appear at most once. For example, {-20, 8, 13} is a set of three integer values. A multiset is like a set, but it allows objects to appear more than once. As an example, {-20, 13, 13, 8, -20, 13} is a multiset, in which -20 appears twice, 8 appears once, and 13 appears three times. Multisets are also called bags. A linked list is a natural way of storing multisets in programs. The above example multiset can be stored as the following linked list: Each member of the multiset is stored as a node in the list, defined in the program as: struct Node {int value; Node *next;}; Observe that each node contains an integer value, and a pointer to the next node in the list. The head of the list can now be declared as: Node *head; Program: Write a C++ program that manages a multiset of integers. This multiset should be initially empty, i.e. it should have no elements to start with. The program should be capable of adding new integer values to the multiset, and counting the number of occurrences in the multiset of a given integer value. The user must be given a choice of these options: 1. Add a new value 2. Count occurrences of a value 3. Quit The result of the user's selection must be displayed, and the menu repeated, until 3 for Quit is chosen.Explanation / Answer
#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>
#include<iostream>
void main()
{
struct node
{
int value;
struct node *ptr;
};
typedef struct node NODE;
NODE *head, *first, *temp = 0, *temp2=0;
int count = 0;
int choice = 1, ch=1;
first = 0;
while(ch!=3)
{
cout << "1. Add New Value 2. Count Occurances 3. Quit ";
cin >> ch;
if(ch==3) break;
if(ch==1)
{
head = (NODE *)malloc(sizeof(NODE));
cout << "Enter the data item ";
cin >> head-> value; //cout << head->value;
if (first != 0)
{
temp->ptr = head;
temp = head;
temp->ptr = 0;
}
else
{
first = temp = head;
}
}
else if(ch==2)
{
int p=0, q=0;
cout <<"Enter no to find ";
cin >>p;
temp2=first;
while (temp2 != 0)
{
if(temp2->value==p)
q++;
temp2 = temp2 -> ptr;
}
cout << p<<" occurs "<<q<<" times ";
}
fflush(stdin);
}
temp->ptr = 0;
temp=first;
while (temp != 0)
{
cout << "=> "<<temp->value;
count++;
temp = temp -> ptr;
}
cout <<" No. of nodes in the list = "<<count<<endl;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.