I'm new here, I need some help with this problem, the problem is that it stores value for the first entry, but when I'm creating a list, for example when I want to insert 22
, after I have inserted 2
before, it behaves as if it added the node after 2
, but actually it doesn't create and I don't know why. Need assistance on this one, please.
void insertKey(int key) {
int i = Hash(key);
Node* temp = HashTable[i];
Node* NewNode = new Node;
NewNode->key = key;
NewNode->next = NULL;
if (temp == NULL) {
HashTable[i] = NewNode;
}
else
{
while (temp != NULL) {
cout << "NOTHere ";
temp = temp->next;
}
if (temp == NULL) {
cout << "FoundYa ";
temp = NewNode;
}
}
}
When you assign temp = NewNode;
you're not actually setting the value of the previous temp->next
to NewNode
. You don't need to set temp
to NewNode
, you need to set temp->next
to NewNode
once temp->next == NULL
.
What you are currently doing is this:
[ node 1 ] --> nullptr
|
|
assign nullptr to temp
|
V
temp <--- then assign NewNode to temp
What you need to do is this:
[ node 1 ] --> nullptr
|
|
assign this to temp
|
V
temp --> nullptr <-- assign NewNode to this