Linked List in c++
I am trying to make a linked list by user input but my code is not able to do it properly. It is printing only first element from the list continuously. Can someone tell me whats wrong with this code? https://code.sololearn.com/cA9a95a159A4
1/19/2021 8:44:57 AMGajendra Sonare
2 AnswersNew Answer
You forgot to advance the pointer like you did in insert(), i.e. head = head->next; Notice that a while loop is not going to print the last data segment, but you could switch to a do-while loop instead. Line 11 will then trigger a warning. NULL is an implementation-defined macro and only meant to be used with pointers. C++ introduced nullptr to replace NULL, which I would recommend using by the way. The real issue with this comparison, however, is if I for example entered 0 1 2 3 4 the code would no longer work correctly, since insert would overwrite the 0 with 1 (at least on GCC, where NULL evaluates to 0). This brings up the question how you know the user has stored data in the root or not. If you don't allocate "root" beforehand, you could instead check if the "root" pointer is a nullptr or not. Last but not least, you are not deleting the allocated memory, which would be a good thing to do.
Is this an assignment? I ask because there is no valid reason to create your own linked list in C++. The C++ Standard Template Library (STL) already has classes for lists, and many other useful data structures, which saves you from the trouble of doing it yourself. https://www.cplusplus.com/reference/list/list/ Remember, C++ is not C.