According to me your Insert code should be like this
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
|
void LinkList::Insert(int num)
{
node **temp, *temp2;
temp = &starting;
temp2 = *temp;
if (temp2 == NULL ) {
temp2 = new node;
cout << "Enter class name: " << endl;
cin >> temp2->y.Class;
cout << "Enter class number: " << endl;
cin >> temp2->y.number;
cout << "Enter class hours: " << endl;
cin >> temp2->y.hours;
temp2->next = NULL;
starting = temp2;
}
else {
while (temp2->next != NULL)
{
temp2 = temp2->next;
}
temp2->next = new node;
temp2 = temp2->next;
cout << "Enter class name: " << endl;
cin >> temp2->y.Class;
cout << "Enter class number: " << endl;
cin >> temp2->y.number;
cout << "Enter class hours: " << endl;
cin >> temp2->y.hours;
temp2->next = NULL;
}
}
| |
Problem with your code was that your linked lists head was not pointing at any address.
How Linked list work is:
the head of the list will point to a address. Then that address will point to another address and so on. Basically, it is like a chain.
So for head to point at anything (in your case starting) it should be passed by reference because you are modifying the head. That's why I did
node **temp = &starting
And then you assign this to a temp2 node. Then check if the node is null.
Condition will be true because in constructor you have specified
starting = NULL;
If the head is null then add the node to the head. And then assign head to this node, hence
starting = temp2
Then for the second entry, when the head will not be NULL, you have to iterate through the list till the next of the node is NULL (since in single linked list this is how we mark the end of the list. When the last next is NULL therefore end of list). Then at this next you will create new node, hence
temp2->next = new node;
then change to this node since you have to assign values to this node
hence
temp2 = temp2-next;
Then assign values
Hope this helps