44.7k views
3 votes
Please modify the Code below so that the User enters the values in the list​​

#include
using namespace std;
// declare the node
struct Node{
int data;
Node *next;
};
class LinkedList {
Node *head; // head pointer
public:
LinkedList() // default constructor
{
head = NULL;
}
// insert the first element
void insert( int val) {
// creates a new node
Node *new_node = new Node;
new_node->data = val;
new_node->next = NULL;
// make the new node the head if the list is empty
if ( head ==NULL)
head = new_node;
else
{
new_node->next = head;
head = new_node;
}
}
void remove(int val)
{
if (head->data == val) {
delete head;
head = head->next; // deleting the head
return;
}
// if there is only one element in the list
if (head->next ==NULL)
{
if ( head->data ==val)
{
delete head;
head = NULL; // assign null to head after removing head
return;
}
cout<< "Value not found"<return;
}
Node*temp = head;
while (temp->next!=NULL)
{
if(temp->next->data ==val)
{
Node* temp_ptr = temp->next->next;
delete temp->next;
temp->next = temp_ptr;
return;
}
temp = temp->next;
}
cout <<"Value not found"<}
void display()
{
Node* temp = head;
while(temp!=NULL)
{
cout<data<<" ";
temp = temp->next;
}
cout<< endl;
}
};

int main()
{
LinkedList l;
l.insert(4);
l.insert(7);
l.insert(13);
cout << "Our list is: " ;
l.display();

cout << "Remove 7"<l.remove(7);
l.display();
}

User LargeTuna
by
8.6k points

1 Answer

1 vote

Final answer:

The user can modify the insert function to allow values to be entered in the list.

Step-by-step explanation:

In the given code, the user can enter values in the list by modifying the insert function.

  1. First, instead of hardcoding the value (like l.insert(4)), you can use cin to take the input from the user.
  2. For example, you can modify the insert function as follows:
void insert() {
int val;
cout << "Enter value: ";
cin >> val;

Node *new_node = new Node;
new_node->data = val;
new_node->next = NULL;

if (head == NULL)
head = new_node;
else {
new_node->next = head;
head = new_node;
}
}

This way, each time the insert function is called, the user will be prompted to enter a value and that value will be inserted in the list.

User SpicyClubSauce
by
8.9k points