linking node at the end of the list

Hi all, I tried to link a new node(NewNode) at the end of the list but it is not executing the last statement (last->next = NewNode). Could you guys help me to solve this problem? Thank you in advance.


[
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Assessment
{
    public:
        string type;
        float mark;
        Assessment *next;
};

class Student
{
    public:
        string ID;
        float cmark;
        Assessment *head;
};

class List
{
    public:
        int index;
        Student record[100];
};

]

[
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
void Quiz(List** first, float score)
{
    Assessment* last = (*first)->record[x].head;
    Assessment* NewNode = new Assessment();
    
    NewNode->type = "Quiz";
    NewNode->next = NULL;
    score = (score / 40) * 15;
    NewNode->mark = score;
    cout << "Percentage of Quiz is " << score << "%" << endl << endl;

    while(last!=NULL)
        last = last->next;

    last->next = NewNode;
}
]
Last edited on
this is subtle. You scroll through the list until last DOES equal NULL. (modern c++ uses nullptr instead of NULL). When it DOES equal NULL, you assign it. That is NOT part of the list, its just a standard NULL pointer!!

what you have to do is like this:
if(last) //same as last != null
while(last->next != null)
last = last->next;
else
last = newnode; //if last was null, it goes here. right?

it is also highly useful to KEEP last as a class member that is always in the correct place so you do not have to loop through the whole list every time you need to add one. Then your insert and delete (and anything else that does this kind of operation) maintain last and use it.

Correction: last is null so last->next is a crash/undefined behavior @ line 15. Regardless, the fix is still to use next off the last one.
Last edited on
Thank you for the information, it's really helpful. Now, I'm able to link all the nodes.
Topic archived. No new replies allowed.