I am having some trouble trying to create a linked list from
I am having some trouble trying to create a linked list from a text file input from user
The three lines
respectively represent a long integer ID of a person, the name of the person, and an
integer ranging from 0 to 5 indicating the threat level posed by a person.
389114
Paul Bunion
5
399012
John Doe
0
685015
Johnny Appleseed
3
179318
Tom Sawyer
2
284139
Ebenezer Scrooge
5
The full connection is: Paul Bunion -> John Doe ->Johnny Appleseed -> Tom Sawyer -> Ebenezer Scrooge.
The task is to read the file content, construct a singly linked list to store the records in a
sequence they appear in the file, and allow flexibility so that users can
perform different operations.
Solution
C ++ CODE:
#include <bits/stdc++.h>
using namespace std;
class node
{
public:
string name = \"\";
long int ID;
int t_level;
node* next = NULL;
};
void insert(long int i, int t_level, string name, node* head)
{
node* tmp = head;
if(tmp->name == \"\")
{
tmp->ID = i;tmp->t_level = t_level; tmp->name = name; tmp->next = NULL;
}
else
{
while(tmp->next != NULL)
{
tmp = tmp->next;
}
node * newnode = new node();
newnode->ID = i;
newnode->t_level = t_level;
newnode->name = name;
newnode->next = NULL;
tmp->next = newnode;
}
}
void display(node* head)
{
node* tmp = head;
if(tmp == NULL)
{
cout << \"Empty list!\" << endl;
}
while(tmp->next != NULL)
{
cout << \"( \" << tmp->name << \", ID = \" << tmp->ID << \" )\" << \" --> \";
tmp = tmp->next;
}
cout << \"( \" << tmp->name << \", ID = \" << tmp->ID << \" )\" << endl;
}
int main()
{
string line;
node* head = new node();
ifstream myfile (\"input2.txt\");
if (myfile.is_open())
{
while ( getline (myfile,line) )
{
long int ID = atol(line.c_str());
getline (myfile,line);
string name = line;
getline (myfile,line);
int t_level = atoi(line.c_str());
insert(ID,t_level,name,head);
}
myfile.close();
}
else
{
cout << \"Unable to open input file\" << endl;
exit(1);
}
display(head);
return 0;
}
input2.txt
389114
Paul Bunion
5
399012
John Doe
0
685015
Johnny Appleseed
3
179318
Tom Sawyer
2
284139
Ebenezer Scrooge
5
Sample Output:
( Paul Bunion, ID = 389114 ) --> ( John Doe, ID = 399012 ) --> ( Johnny Appleseed, ID = 685015 ) --> ( Tom Sawyer, ID = 179318 ) --> ( Ebenezer Scrooge, ID = 284139 )


