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
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started