Reputation: 493
I am writing a simple function to insert at the end of a linked list on C++, but finally it only shows the first data. I can't figure what's wrong. This is the function:
node* Insert(node* head, int data)
{
if (head == NULL) {
head = new node();
head->data = data;
head->link = NULL;
return head;
}
else {
node* temp = head;
while (temp != NULL) {
temp = temp->link;
}
node* temp2 = new node();
temp2->data = data;
temp2->link = NULL;
(temp->link) = temp2;
return head;
}
}
Upvotes: 2
Views: 11633
Reputation: 26717
node* Insert(node* head, int data)
{
if (head == NULL) {
head = new node();
}
else {
while (head->link != NULL) {
head = head->link;
}
head = head->link = new node();
}
head->data = data;
head->link = NULL;
return head;
}
Upvotes: 0
Reputation: 85767
You can simplify your logic by doing this:
void Insert(node **pnode, int data)
{
while (*pnode) {
pnode = &(*pnode)->link;
}
*pnode = new node(data, NULL);
}
assuming you have a node
constructor that initializes data
and link
from arguments.
Instead of calling it as
head = Insert(head, 42);
you'd now do
Insert(&head, 42);
Upvotes: 2
Reputation: 10430
Change the condition in while
construct from:
while (temp!=NULL) {
temp=temp->link;
}
To
while (temp->link!=NULL) {
temp=temp->link;
}
In statement, temp->link = temp2
, temp is a null pointer. You were dereferencing a NULL
pointer.
To append a node at the back, temp
pointer should point to the last node of the linked list. So, in the while
loop, you need to just stop linked list traversal when you have reached the last node, i.e, the node whose link
member points to nothing (has NULL
). while (temp->link!=NULL)
will stop at the last node as last node will have link
member pointing to NULL
.
Upvotes: 3