-
-
Save qwasfun/174b428587ba241c4724f2c63ccf10bf 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
| // 双链节点 | |
| class DoubleLinkNode extends LinkNode { | |
| constructor(element, next, prev) { | |
| super(element, next); | |
| this.prev = prev; // 新增 prev 属性 | |
| } | |
| } | |
| // 双链表 | |
| class DoubleLinkList extends LinkList { | |
| constructor(equalsFn = defaultEquals) { | |
| super(equalsFn); // 初始化 equalsFn、 count、 head属性 | |
| this.tail = undefined; // 新增属性 | |
| } | |
| insert(element, index) { | |
| if (index >= 0 && index < this.count) { | |
| const node = new DoubleLinkNode(element); | |
| let current = this.head; | |
| if (index == 0) { | |
| // 第一个位置插入 | |
| if (this.head == null) { | |
| this.tail = node; | |
| } else { | |
| node.next = this.head; | |
| current.prev = node; | |
| } | |
| } else if (index === this.count) { | |
| // 最后一个位置插入 | |
| current.next = node; | |
| node.prev = current; | |
| this.tail = node; | |
| } else { | |
| // 中间位置插入 | |
| const previous = this.getElementAt(index - 1); | |
| current = previous.next; | |
| previous.next = node; | |
| node.next = current; | |
| node.prev = previous; | |
| current.prev = node; | |
| } | |
| this.count++; | |
| return true; | |
| } | |
| // 添加失败 | |
| return false; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment