I have simple question on C++ linked list. Say I am given a list, I just want to print for each node the value. I found this simple code on the net
while (head!= NULL) {
cout << head->data;
head= head->next;
}
which works just fine.
If I do the following
cout << head->data;
head= head->next;
cout << head->data << endl;
I get the following error (on LeetCode)
Line 20: Char 25: runtime error: member access within null pointer of type 'ListNode' (solution.cpp) SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior prog_joined.cpp:29:25
I do not understand what I am missing.
head=head->nextand then useheadwithout checking whether its null or not. If null, usinghead->datawill cause some trouble.fmt::printlin("{}", fmt::join(listname, ", "));You seem to not want a loop? What would your proposed solution look like if the list contains 3 elements? 200? And given that you're working on a LeetCode solution, are you restricted to the standard library, or is this for personal checks before cleaning up for submission?