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
The most likely issue here is that you cannot use
Insert
to "jump start" your list: if thehead
isNULL
to start with, the loop is going to fail right away. Moreover, on the first insertion you wouldn't be able to assign thehead
.To fix this problem, change the first parameter from
Node *head
toNode **pHead
, pass a pointer to the head pointer, and add an extra level of dereference to the code of yourInsert
function:Note that this approach is going to work even if you pass a pointer to
Node
pointer that is set toNULL
: