使用javaScript来实现一个有序链表

const Compare = {
    LESS_THAN:-1,
    BIGGER_THAN:1
};
function defaultCompare(a,b){
    if(a === b){
        return 0;
    }
    return a < b?Compare.LESS_THAN : Compare.BIGGER_THAN;
}
class SortedLinkedList extends LinkedList{//LinkedList这个类可以见https://www.cnblogs.com/MySweetheart/p/13212220.html
    constructor(equalsFn = defaultEquals, compareFn = defaultCompare){
        super(equalsFn);
        this.compareFn = compareFn;
    }
    insert(element,index = 0){
        if(this.isEmpty()){
            return super.insert(element,0);
        }
        const pos = this.getIndexNextSortedElement(element);
        return super.insert(element,pos);
    }
    getIndexNextSortedElement(element){
        let current = this.head;
        let i = 0;
        for(;i < this.size() && current; i++){
            const comp = this.compareFn(element,current.element);
            if(comp == Compare.LESS_THAN){
                return i;
            }
            current = current.next;
        }
        return i;
    }
}

 

posted @ 2020-07-01 08:16  放学别跑啊  阅读(192)  评论(0编辑  收藏  举报