1 2 3 4 5 6 7
|
//Node * freshNodePtr = new Node(n); // My instructor recommended this line of code in class
Node* currentNodeptr = firstNodePtr;
if (firstNodePtr == nullptr) // If the list has no entries yet, sets the firstNodePtr to that entry
{
firstNodePtr = &n;
}
|
Taking the address of n may be risky. if main has something like
1 2 3 4 5 6 7
|
Node n;
for(everything the user types in)
{
n.something = input;
n.other = more input;
list.insert(n);
}
|
then you will end up with a very messed up list.
if you get a new one each time in insert and copy the data from the incoming n into the new memory, your list may fare better.
what you did can work, but you have to make it work and its subtle how to do that.
See if getting fresh memory each insert helps with the issues you are seeing. I don't see anything else major, but I did not dig into it looking for trouble either.
if you recall your C well, new is akin to malloc, and delete is akin to free.
new gets a chunk of ram big enough to store the type.
so new node gives you a pointer to a new piece of memory big enough to hold a node object. every call to new must be matched to a delete later, but for now, you can let that slide until you have your insert working.
the idea is that you start with a null node pointer.
you get a node data chunk from user or file or something to put into the list.
so you ask for a new piece of memory, and that becomes the list head, and its next pointer is now null.
Then you get another piece of data, and you ask for more memory, and then you either say head -> next is the new item, or new item -> next is head, depending on which comes first (I see you call it ordered list so I assume you want to sort the data as you insert it). When you get the new piece of data, its next pointer should start out as null. So for a moment you have head, whos next is null, and temp, whos next is null. say head is to come first: head->next is assigned to temp. now your list is head, temp, null because temp's next is still set null, head's next is set temp. it begins to chain up that way and each iteration you do this. And if you insert in the middle of two nodes, say the above chain now you want to go head, third guy, second guy as your list, you have to break and assign the pointers in the right order so you don't lose any of them. If you ever have memory chunk with no variable holding that address, its gone. Does that make sense?
A picture may help, you can google animated linked lists to get a feel for what you are wanting to do visually.