使用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; } }