Reputation: 11
I'm trying to insert an object (bird) that holds a name and an ID number I'm having problems inserting the object into my linked list
bool List342::Insert(Bird *obj)
{
Node *insNode = new Node;
insNode->data = obj;
if (head == NULL)
{
head = insNode;
return true;
}
//cout << head->data->getID();
if ((insNode->data->getID()) <= (head->data->getID()))
{
insNode->next = head;
head = insNode;
return true;
}
Node *pNode = head;
while ((pNode->next != NULL) && ((pNode->next)->data->getID() <= insNode->data->getID()))
{
pNode = pNode->next;
}
insNode->next = pNode->next;
pNode->next = insNode;
return true;
}
It doesn't seem to insert correctly I tried putting a cout code to see what numbers are being compared for example cout << head->data->getID() and it seems to output the current id of the current bird and not the id of the head (should be the lowest ID)
please and thank you!
Upvotes: 0
Views: 113
Reputation: 21
The function is working fine for me. I hope, the head is change outside of the insert function. Shall you check the calling portion of the insert or any other places modifying the head value.
Upvotes: 1
Reputation: 311126
I do not see where the function would return false
. So I think there is no any sense to declare the function as having return type bool
because it always returns true
.
I have declared the functtion as having return type void
though you may declare the function as having return type bool
as before but in this case you need to add last statement that will return true
.
Maybe it would be better to declare the function as returning a reference to the list itself.
The function could be defined the following way
void List342::Insert( Bird *bird )
{
Node *prev = NULL;
Node *current = head;
while ( current != NULL && !( bird->getID() < current->data->getID() ) )
{
prev = current;
current = current->next;
}
Node *newnode = new Node { bird, current };
if ( prev != NULL ) prev->next = newnode;
else head = newnode;
}
I suppose that Node has the following definition
struct Node
{
Bird *data;
Node *next;
};
You may substitute statement
Node *newnode = new Node { bird, current };
for
Node *newnode = new Node;
newnode->data = bird;
newnode->next = current;
Upvotes: 2