Hi, I have to write an assignment in C++ for my programming class. This is the f
ID: 3622382 • Letter: H
Question
Hi, I have to write an assignment in C++ for my programming class. This is the first part of the assignment and I am having trouble writing it. Please help me!!In this assignment, you are to build singly linked lists, according to the given criteria.
The structure is defined as
struct Node {
string name;
long ID;
Node * next;
};
This assignment includes:
1. Write a function that will read from a file with the filename as the parameter of the function. In the function, it will do:
a. Read one person’s information at a time, and build a singly linked list according to the ascending order of the person’s ID.
Result: a singly linked list should have its first node to store the info with the smallest ID value, the second node to store the info with the next smallest ID value, and so on.
b. Pass out the head pointer as in return.
This is the file:
AprilJoe 129013
MatthewsJocob 399921
GarfieldKitty 332901
LakeBill 211254
JonesBetty 182890
GoodmanBetty 195106
LandsNorman 365920
JohnsonCarl 297192
This is how I would think to write it. First I used the a read function, the I sorted it using bubblesort and then I would read it again. Here is what I have so far.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
struct Node {
string name;
long ID;
Node * next;
};
Node * read (string fileName);
void print(Node * list);
int main()
{
Node * list;
list = read("a9.txt");
print(list);
system ("PAUSE");
return 0;
}
Node * read (string fileName)
{
Node * list = NULL;
Node * cur = NULL;
ifstream myfile;
myfile.open("a9.txt");
if(!myfile.is_open())
{
cout << "Cannot open " << fileName << endl << endl;
return NULL;
}
string garbage;
while (!myfile.fail())
{
Node * temp = new Node();
getline(myfile, temp->name);
myfile >> temp->ID;
getline(myfile, garbage);
getline(myfile, garbage);
temp->next = NULL;
if (list == NULL)
{
list = temp;
}
if (cur == NULL)
{
cur = temp;
}
else
{
cur->next = temp;
cur = cur->next;
}
}
myfile.close();
return list;
}
void print(Node * list)
{
Node * cur = list;
while(cur != NULL)
{
cout << "Name: " << cur->name << endl;
cout << "ID: " << cur->ID << endl;
cur = cur->next;
}
}
void sort(node * next)
{
int x;
int y;
int temp;
node * next;
for(x=size; x>0; x--)
{
for(y=0; y<x-1; y++)
{
if(node->name>node->name)
{
temp = node -> name;
node -> name = node -> name;
node -> name = temp;
}
}
}
cout << "SORTED LIST ACCORDING TO ID NUMBERS:" << endl << endl;
for (int i = 0; i < size; i++)
{
cout << "Name: " << node -> name<< endl;
cout << "ID: " << node -> ID << endl;
}
}