用js实现数据结构之链表

493 阅读1分钟

链表是链式数据结构中的一种,是不连续的内存空间,每个节点分别保存自身的数据和下一个节点的内存地址,其中es6中的Map即采用的链表结构。本章就模拟Map实现一下链表的原理。

先定义构造函数myMap

function myMap(){
    this.bucketLength = 8
    this.init()
}

<!--开始-->
myMap.prototype.init = function(){
    this.bucket = new Array(this.bucketLength);
    for(let i = 0; i< this.bucket.length; i++ ){
        this.bucket[i] = {
            type: 'bucket_' + i,
            next : null
        }
    }
}
<!--判断数据类型-->
myMap.prototype.makeHash = function(key){
    let hash = 0;
    if(typeof key !== 'string'){
        if(typeof key == 'number'){
            hash = Object.is(key, NaN) ? 0 :key
        }else if(typeof key == 'object'){
            hash = 1
        }else if(typeof key == 'boolean'){
            hash = Number(key);
        }else{
            hash = 2
        }
    }else{
        for(let i = 0; i< 3; i++){
            hash += key[i] ? key[i].charCodeAt(0) : 0;
        }
    }

    return hash % 8
},
<!--插入值-->
myMap.prototype.set = function(key, value){
    let hash = this.makeHash(key);
    let oTempBucket = this.bucket[hash];
    while(oTempBucket.next){
        if(oTempBucket.next.key == key){
            oTempBucket.next.value = value 
        }else{
            oTempBucket = oTempBucket.next;
        }
    }
    oTempBucket.next = {
        key: key,
        value: value,
        next: null
    }
}
<!--获取值-->
myMap.prototype.get = function(key){
    let hash = this.makeHash(key);
    let oTempBucket = this.bucket[hash];
    while(oTempBucket){
        if(oTempBucket.key == key){
            return oTempBucket.value
        }else{
            oTempBucket = oTempBucket.next
        }
    }

    return undefined
}
<!--删除值-->
myMap.prototype.delete = function(key){
    let hash = this.makeHash(key);
    let oTempBucket = this.bucket[hash];
    while(oTempBucket){
        if(oTempBucket.key == key){
            oTempBucket.next = oTempBucket.next.next
            return true
        }else{
            oTempBucket = oTempBucket.next
        }
    }
}
<!--判断值是否存在-->
myMap.prototype.has = function(key){
    let hash = this.makeHash(key);
    let oTempBucket = this.bucket[hash];
    
    while(oTempBucket){
        if(oTempBucket.next && oTempBucket.next.key == key){
            return true
        }else{
            oTempBucket = oTempBucket.next
        }
    }

    return false
}
<!--清除整个链表-->
myMap.prototype.clear = function(){

    this.bucket = new Array(8)
}

let mymap = new myMap();