使用单链列表在哈希表中插入

问题描述 投票:-3回答:1

我是新来的,我需要一些帮助来解决这个问题,问题在于它存储了第一个条目的值,但是当我创建列表时,例如,当我想插入22时,在2之前插入过,它的行为就像在2之后添加了节点一样,但是实际上它没有创建,我也不知道为什么。在这方面需要帮助。

 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;
            }
        }
    }
c++ hashtable singly-linked-list
1个回答
1
投票

分配temp = NewNode;时,实际上并没有将前一个temp->next的值设置为NewNode。您无需将temp设置为NewNode,只需将temp->next设置为NewNode

您当前正在做什么:

temp->next == NULL

您需要执行的操作是:

[ node 1 ] --> nullptr
                 |
                 |
        assign nullptr to temp
                 |
                 V
                temp <--- then assign NewNode to temp
© www.soinside.com 2019 - 2024. All rights reserved.