Question: Could you solve this problem using C++? ---------------------------------------------- Please use the attached code and add a new function to this code. This function will add

Could you solve this problem using C++?

----------------------------------------------

Please use the attached code and add a new function to this code. This function will add a new node in order to a given linked list. As such it will be called addInOrder, and its prototype will be:

void addInOrder(Node* &head, int key);

As an example of how this function will work, supposed we had the list 2 6 9 13 and we wanted to add the number 10. The new list would be 2 6 9 10 13.

Please call this function in the main function in place of add. Currently, 10 random numbers are added to the list, but they should now be added in order. The for loop should look like this:

// build a linked list

for(int i = 0; i < 10; i++) {

addInOrder(head, rand()%100);

}

-------------------------------------------------------

#include

using namespace std;

struct Node {

int data;

Node* next;

};

void print(Node* curr);

void add(Node* &head, int key);

bool search(Node* head, int key);

void remove(Node* &head, int key);

int main() {

// declare vars

Node* head = NULL;

// build a linked list

for(int i = 0; i < 10; i++) {

add(head, rand()%100);

}

// print it

print(head);

// do a search

cout << search(head, 20) << endl;

remove(head, 86);

remove(head, 86);

remove(head, 20);

print(head);

return 0;

}

void remove(Node* &head, int key) {

// if search fails, quit

if(!search(head, key)) {

return;

}

// we want to remove the head

if(head->data == key) {

Node* toDelete = head;

head = head->next;

delete toDelete;

return;

}

// find the node before the one with the key

Node* curr = head;

while(curr->next->data != key) {

curr = curr->next;

}

// remove the node with key

Node* toDelete = curr->next;

curr->next = curr->next->next;

delete toDelete;

}

bool search(Node* head, int key) {

while(head != NULL) {

if(head->data == key) {

return true;

}

head = head->next;

}

return false;

}

void add(Node* &head, int key) {

// add at the front of the list

Node* newnode = new Node; // make a new node

newnode->data = key; // put data in it

newnode->next = head; // point it at the first node

head = newnode; // point the head at it

}

void print(Node* curr) {

while(curr != NULL) {

cout << (*curr).data << " ";

curr = curr->next;

}

cout << endl;

}

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!