Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

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;
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote