I'm working on a practice problem with linked list,
the program is supposed to read in a list of student scores and add it to a list, until input score is -1, which indicates user is done with the input.
program is supposed to print the list and number of nodes in it, and then sort all the scores into 4 lists for grades A, B, C, F, and then print each of the four lists.
for example,
for input: 23 77 89 99 67 12 65 55 44 50 99 100 50 88 76 40 -1
output would be:
SCORES: 23 77 89 99 67 12 65 55 44 50 99 100 50 88 76 40 contains 16 nodes
A_LIST: 99 99 100 contains 3 nodes
B_LIST: 89 88 contains 2 nodes
C_LIST: 77 76 conatins 2 nodes
F_LIST: 23 67 12 65 55 44 50 50 40 contains 9 nodes
right now my code keeps crashing, I am new to linked list and the topic gets me pretty confused, can someone help me figure what's the problem? Thanks!!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105
|
#include <iostream>
using namespace std;
struct Node
{
int data;
Node * link;
};
void get_input(Node*&head_ptr)
{
//reads in a list of exam scores (int 0-100) from the keyboard
//and creates a linked list of integers by adding each new number to the tail end of the list.
int n;
// n = head_ptr->data;
Node*temp;
temp = head_ptr;
cin>>n;
while (n != -1)
{
temp->link = new Node;
temp = temp->link;
temp->data = n;
temp->link = NULL;
cin>>n;
}
}
void display_and_count(Node*&head_ptr)
{
//prints the original list and prints out how many nodes were on the list.
int count=1;
Node*next;
next = head_ptr;
while (next->link != NULL)
{
cout << next->data;
next = next->link;
count++;
}
cout<<"contains "<<count<<" nodes.";
}
void split_them_up(Node*&head_ptr, Node*a, Node*b, Node*c, Node*f)
{
//a, b, c, f, originally empty; separate x into 4 lists
// SCORES should be empty afterwards
//preserve order, each new addition made to the tail of list
Node*temp;
temp = head_ptr;
while (temp->link != NULL)
{
if (temp->data >= 90)
{
a->link = temp;
a = a->link;
}
else if (temp->data >= 80)
{
b->link = temp;
b = b->link;
}
else if (temp->data >= 70)
{
c->link = temp;
c = c->link;
}
else
{
f->link = temp;
f = f->link;
}
temp = temp->link;
}
}
int main ()
{
Node *SCORES = NULL;
Node *A_LIST = NULL;
Node *B_LIST = NULL;
Node *C_LIST = NULL;
Node *F_LIST = NULL;
get_input(SCORES);
cout<<"SCORES: ";
display_and_count(SCORES);
split_them_up(SCORES, A_LIST, B_LIST, C_LIST, F_LIST);
cout<<"A_LIST: ";
display_and_count(A_LIST);
cout<<"B_LIST: ";
display_and_count(B_LIST);
cout<<"C_LIST: ";
display_and_count(C_LIST);
cout<<"F_LIST: ";
display_and_count(F_LIST);
}
|