新元素未附加到链接列表的开头

用26个键(字母字母)制作一个简单的哈希表,该键可以容纳各种单词。

如果发生冲突(比方说,两个单词的首字母相同),我将在哈希表中创建一个链接列表。

为了使事情更快一点,在将新单词放入哈希表时,我想将其附加到列表的开头,而不是遍历整个列表以添加单词。

因此,假设我有一个链接列表:

{"test","towel","taxes"} 0 1 2 我添加了部队一词:

{"troop","test","taxes"} 0 1 2 3

这是我的代码:

class Node{
    constructor(word){
        this.word = word;
        this.next = null;
    }
}

class Hashtable{
    constructor(size = 26){
        this.table = new Array(size);
    }

    put(word){ // adds a word to a hashtable
        let key = word[0]; // this hashtable is really simple,the key will be the word's first letter
        let node = new Node(word); // creates a node that contains the word and a pointer to the next node

        if(this.table[key] == undefined){ // if this hash table has never been used before,intiialize it
            this.table[key] = node;
        }
        else{ // appends the node (word) to the BEGINNING of the linked list 
            node.next = this.table[key]; // sets the node's pointer to the first element of the linked list. 
            this.table[key] = node; // the first element of the list now points to this node
        }
        console.log(this.table[key]);
    }
}

现在我添加这些词:

hashtable.put("test");
hashtable.put("toto");

这是问题所在:

新元素未附加到链接列表的开头

即使我在最后附加“ toto”,也不会转到列表的开头。

有办法吗?

zhweb1 回答:新元素未附加到链接列表的开头

暂时没有好的解决方案,如果你有好的解决方案,请发邮件至:iooj@foxmail.com
本文链接:https://www.f2er.com/3169833.html

大家都在问