Create a C++ program that finds the location, from the list of elements in an ar
ID: 3848760 • Letter: C
Question
Create a C++ program that finds the location, from the list of elements in an array. The program should return the location of the element, and returns -1 if the element if not found. Test the function by passing various data to it. a) Your program should also ask the user to enter the number of elements that will be presented in the list. b) Ask the user to input the elements c) Ask for the element to search for Where all is the list of elements, N is the number of elements, and e is the element to search.Explanation / Answer
/*
* C++ Program to Implement Singly Linked List
*/
#include<iostream>
#include<cstdio>
#include<cstdlib>
using namespace std;
/*
* Node Declaration
*/
struct node
{
int info;
struct node *next;
}*start;
/*
* Class Declaration
*/
class single_llist
{
public:
node* create_node(int);
void insert_last();
void search();
single_llist()
{
start = NULL;
}
};
/*
* Main
*/
main()
{
int nodes, i;
single_llist sl;
start = NULL;
cout<<"Enter number of element to be inerted ";
cin>>n;
for (i=0; i<n; i++)
{
sl.insert_last();
}
cout<<"Search element in Link List: "<<endl;
sl.search();
cout<<endl;
}
/*
* Creating Node
*/
node *single_llist::create_node(int value)
{
struct node *temp, *s;
temp = new(struct node);
if (temp == NULL)
{
cout<<"Memory not allocated "<<endl;
return 0;
}
else
{
temp->info = value;
temp->next = NULL;
return temp;
}
}
/*
* Inserting elements
*/
void single_llist::insert_last()
{
int value;
cout<<"Enter the value to be inserted: ";
cin>>value;
struct node *temp, *s;
temp = create_node(value);
s = start;
while (s->next != NULL)
{
s = s->next;
}
temp->next = NULL;
s->next = temp;
cout<<"Element Inserted at last"<<endl;
}
/*
* Searching an element
*/
void single_llist::search()
{
int value, pos = 0;
bool flag = false;
if (start == NULL)
{
cout<<"List is empty"<<endl;
return;
}
cout<<"Enter the value to be searched: ";
cin>>value;
struct node *s;
s = start;
while (s != NULL)
{
pos++;
if (s->info == value)
{
flag = true;
cout<<pos<<endl;
}
s = s->next;
}
if (!flag)
cout<<-1<<endl;
}