-
-
Save qwasfun/3e2d4e08b56b4dc6776cd0612e926a7b to your computer and use it in GitHub Desktop.
有序列表,是指保持元素有序的链表结构
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| const Compare = { | |
| LESS_THAN: -1, | |
| GREATER_THEN: 1, | |
| }; | |
| function defaultCompare() { | |
| if (a === b) { | |
| return 0; | |
| } | |
| return a < b ? Compare.LESS_THAN : Compare.GREATER_THEN; | |
| } | |
| class SortedListLint extends LinkList { | |
| 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); | |
| } | |
| /** | |
| * 迭代整个有序链表直达找到需要插入元素的位置,或是迭代完所有元素 | |
| * @param {*} element 待查找元素 | |
| * @returns 待查找元素索引 | |
| */ | |
| getIndexNextSortedElement(element) { | |
| let current = this.head; | |
| let i = 0; | |
| for (; i < this.size; i++) { | |
| const comp = this.compareFn(element, current.element); | |
| if (comp === comp.LESS_THAN) { | |
| return i; | |
| } | |
| current = current.next; | |
| } | |
| return i; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment