First, thanks in advance for all of you who respond to this post.
Second, I\'ve looked through all other posts and couldn\'t find anything that helped me (my apologies,
The most likely issue here is that you cannot use Insert
to "jump start" your list: if the head
is NULL
to start with, the loop is going to fail right away. Moreover, on the first insertion you wouldn't be able to assign the head
.
To fix this problem, change the first parameter from Node *head
to Node **pHead
, pass a pointer to the head pointer, and add an extra level of dereference to the code of your Insert
function:
Node* Insert(Node **pHead, int data)
{
while(*pHead != NULL){
pHead = &((*pHead)->next);
}
Node *last = new Node();
last -> data = data;
last -> next = NULL;
*pHead = last;
return last;
}
Note that this approach is going to work even if you pass a pointer to Node
pointer that is set to NULL
:
Node *head = NULL;
Insert(&head, 1);
Insert(&head, 2);
Insert(&head, 3);