Add a new function bool search(int value) to check whether value is present in t
ID: 3547047 • Letter: A
Question
Add a new function
bool search(int value)
to check whether value is present in the linked list. Function should return true if value is found, false otherwise.
#include <iostream>
#include <fstream>
#include <iomanip>
#include <cassert>
using namespace std;
struct Node {
int value;
Node *next;
};
Node *head = NULL;
Node *tail = NULL;
//insert at the end
void insert(int input)
{
//get new box ready
Node *temp = new Node;
temp->value = input;
temp->next = NULL;
if (tail) {
//list is not empty
tail->next = temp; //add new node at end
tail = temp; //make new node as new tailnode
} else {
//list is empty
head = tail = temp;
}
}
void print() {
Node *temp = head;
if (!temp)
cout << "Empty";
while (temp) {
cout << temp->value << " ";
temp = temp->next;
}
cout <<endl;
}
int deleteFirst() {
//not part of deleteFirst() functionality!
assert(head != NULL); //use for debugging
//get the value from first box
int out = head->value;
//first box needs to be deleted
//so, keep track of it using temp
Node *temp = head;
//make head point to 2nd box
head = head->next;
if (!head)
tail = NULL;
//delete first box
delete temp;
return out;
}
main() {
int x;
while (true) {
cout << "Enter next value to insert (-1 to end): ";
cin >> x;
if (x < 0)
break;
insert(x);
}
print();
cout << "First item: " << deleteFirst() << endl;
cout << "2nd item: " << deleteFirst() << endl;
print();
}
Explanation / Answer
//search function
bool search(int value) {
struct Node *temp=head;
while(temp!=NULL){
if(temp->value == value){
return true;
}
temp = temp->next;
}
return false;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.