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, I'm new to C++).
Here's my code:
Node* Insert(Node *head,int data) //for linked lists
{
Node* current = head;
while(current -> next != NULL){
current = current -> next;
}
cout << head -> data;
Node *last = new Node();
last -> data = data;
last -> next = NULL;
current -> next = last;
return head;
}
It seems (by trial and error of line commenting) that the access of the next attribute in the current pointer seems to be the problem, yet I can't seem to figure out why. The Node struct has two attributes, *next (which points to the next item in the linked list) and data (the data of the node).
Any ideas of what's going on?
linuxuser
EDIT: The problem was solved - thanks so much to all who left comments!
Sadly, I wasn't able to use the **pHead
dereferencing solution, as the problem is on a website that auto-inputs the arguments for the function. Using the comments below, however, I made a simple program that I hope will detail this issue for other beginning C++ programmers like me:
Node* Insert(Node *head,int data)
{
if(head == NULL){
Node* last = new Node();
last -> data = data;
return last;
}
Node *current = head;
while(current -> next != NULL){
current = current -> next;
}
Node *last = new Node();
last -> data = data;
last -> next = NULL;
current -> next = last;
return head;
}
Regards,
linuxuser