This program does NOT need to use classes or dynamically allocated arrays This p
ID: 3571996 • Letter: T
Question
This program does NOT need to use classes or dynamically allocated arrays
This program does NOT need to use external data files a
Instead, create a program that will store subject information (sorted by subject) from the user, build a linear linked list inserting the data in sorted order, and display the information (traversing the entire LLL). It should continue to do this as long as the user wants.
At the end make sure to deallocate the memory.
- you are not allowed to use global variables. You are allowed to use the cstring library (e.g., strlen, strcpy, and strcmp). Limit your main (and all functions) to no more than 30 statements of code (for executable statements... not counting variable definitions, blank lines, lines with just curly brackets, or comments).
- separate out your code into a .h file and at least two .cpp files. The .h file should contain the (a) #includes, (b) constants, (c) prototypes, (d) struct definitions, and (e) class interface(s) – if you are using a class. Your struct node should be placed in the .h file. Never place the implementation of your functions in a .h file; these belong in a .cpp file!
Explanation / Answer
// in sort.h
//declaration
class Sort
{
public:
struct node{
string subject;
node *next;
};
node *A = NULL;
int choice, count;
ifstream subject File;
};
// in sort.cpp
//in insert operation
#include "sort.h"
void Sort::insert(string subject){
node *insert,
*last,
*current;
insert = new node;
insert->subject = subject;
if (A == NULL){
insert->next = A;
A = insert;
}else{
current = A;
last = A;
while (current && current->subject < subject){
last = current;
current = current->next;
}
if (current == A){
/* Insert before 1st node */
insert->next = A;
A = insert;
}
else{
/* Insert between last and current
or at the end of the list */
last->next = insert;
insert->next = current;
}
}
}
//display elements
void Sort:: display()
{
node *curr;
curr = A;
while(curr){
if(A == NULL){break;}
cout << A->subject << endl;
A = A->next;
}
}
}
//in mainfunction.cpp
#include "sort.h" // defines sort
int main(){
count = 0;
subjectFile.open("subject.txt");
string item;
string name;
while(subjectFile)
{
subjectle >> item;
insertnode(item);
count++;
}
cout << "1. Display the linked list ";
cout << "2. Display the length of the list ";
cin >> choice;
switch (choice)
{
case 1:
display();
break;
case 2:
cout << "There are " << count - 1 << " subjects in the list ";
break;
}
system("PAUSE");
return 0;
}
// in sort.h
//declaration
class Sort
{
public:
struct node{
string subject;
node *next;
};
node *A = NULL;
int choice, count;
ifstream subject File;
};
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.