In: Computer Science
Write a program to remove the node of Fruit type which contains “Banana” from a given linked list and then print the updated linked list. Part of the program is given below but it is incomplete. You need to complete it. You should create your own data file. After you complete the program, please check it carefully to ensure it can handle the following cases:
Banana is the first node in the linked list.
Banana is not the first node in the linked list.
Banana doesn’t exist in the linked list.
Note that head should points to the first node of the linked list even after you remove the node which contains “banana”.
#include<iostream>
#include<string>
#include<fstream>
using namespace std;
struct Fruit{
string strF;
Fruit* next;
};
int main()
{
ifstream myfile;
myfile.open("test.txt");
Fruit * head = 0;
Fruit f;
myfile >> f.strF;
f.next = head;
head = &f;
Fruit f1;
myfile >> f1.strF;
f1.next = head;
head = &f1;
Fruit f2;
myfile >> f2.strF;
f2.next = head;
head = &f2;
//print the linked list:
cout<<"Print the linked list before the insertion:"<<endl;
Fruit * t = head;
while(t!= 0)
{
cout << t->strF << "--->"<<endl;
t = t->next;
}
cout<<endl;
//Write your code here to delete the node which has "banana"
cout<<"Print the linked list after the insertion:"<<endl;
//print the updated linked list
return 0;
}
#include<iostream>
#include<string>
#include<fstream>
using namespace std;
struct Fruit {
string strF;
Fruit* next;
};
bool check(Fruit* a)
{
if (a->strF == "Banana")
{
return true;
}
return false;
}
int main()
{
ifstream myfile;
myfile.open("file1.txt");
Fruit * head = 0;
Fruit f;
myfile >> f.strF;
f.next = head;
head = &f;
Fruit f1;
myfile >> f1.strF;
f1.next = head;
head = &f1;
Fruit f2;
myfile >> f2.strF;
f2.next = head;
head = &f2;
//print the linked list:
cout << "Print the linked list before the
insertion:" << endl<<endl;
Fruit * t = head;
int count = 0;
while (t != 0)
{
if (count == 0)
cout <<
t->strF;
else
cout <<
"--->" << t->strF;
t = t->next;
count++;
}
cout << endl << endl;;
//Write your code here to delete the node which has
"banana"
cout << "Print the linked list after the
insertion:" << endl<<endl;
t = head;
Fruit* temp = head;
string notb;
notb = t->strF;
if (check(t))
{
head = head->next;
t = head;
temp = head;
}
t = t->next;
while(t!=0)
{
if (check(t))
{
temp->next =
t->next;
t =
t->next;
}
temp = temp->next;
t = t->next;
}
t = head;
count = 0;
while (t != 0)
{
if(count==0)
cout << t->strF;
else
cout<<"--->" <<
t->strF;
t = t->next;
count++;
}
cout << endl<<endl;
//print the updated linked list
system("pause");
return 0;
}
Comment Down For Any Queries
Please Give A Thumbs Up If You Are Satisfied With The Answer