【问题标题】:Insertion in Hash Table using Singly Linked Lists使用单链表在哈希表中插入
【发布时间】:2020-08-25 02:29:51
【问题描述】:

我是新来的,我需要一些帮助来解决这个问题,问题是它存储了第一个条目的值,但是当我创建一个列表时,例如当我想插入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;
            }
        }
    }

【问题讨论】:

  • 当您分配temp = NewNode 时,您实际上并未将之前的temp-&gt;next 的值设置为NewNode。您不需要将temp 设置为NewNode,您需要将temp-&gt;next 设置为NewNode 一次temp-&gt;next == NULL
  • 先生,您是救命稻草。
  • 我需要理解这个(temp->next)逻辑,为什么它不能与我使用的上述逻辑一起工作,你能帮我更好地理解吗?
  • @ShaharyarKhan 表示问题已解决的首选方式是接受解决问题的答案,而不是编辑标题。

标签: c++ hashtable singly-linked-list


【解决方案1】:

当您分配temp = NewNode; 时,您实际上并未将之前的temp-&gt;next 的值设置为NewNode。不需要将temp 设置为NewNode,只需将temp-&gt;next 设置为NewNode 一次temp-&gt;next == NULL

你目前正在做的是:

[ node 1 ] --> nullptr
                 |
                 |
        assign nullptr to temp
                 |
                 V
                temp <--- then assign NewNode to temp

你需要做的是:

[ node 1 ] --> nullptr
    |
    |
  assign this to temp
    |
    V
   temp --> nullptr <-- assign NewNode to this

【讨论】:

  • 先生,再清楚不过了,非常感谢,感谢您的帮助。
猜你喜欢
  • 2015-04-11
  • 2015-06-25
  • 2017-03-28
  • 2015-06-10
  • 1970-01-01
  • 1970-01-01
  • 2015-11-08
  • 2015-03-07
相关资源
最近更新 更多