Created
August 6, 2018 07:18
-
-
Save giscafer/405d146bfbde600038c7f4e8e8fdf210 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 LinkNode { | |
| constructor(element) { | |
| this.element = element; | |
| this.next = null; | |
| } | |
| } | |
| /* 链表类 */ | |
| class LinkedList { | |
| constructor() { | |
| this.length = 0; | |
| this.head = null; | |
| } | |
| append(element) { | |
| let current = null; | |
| let node = new LinkNode(element); | |
| // 第一个 | |
| if (this.head === null) { | |
| this.head = node; | |
| } else { | |
| // 查找最后一个 | |
| current = this.head; | |
| while (current.next) { | |
| current = current.next; | |
| } | |
| current.next = node; | |
| } | |
| this.length++; | |
| } | |
| insert(position, element) { | |
| if (position >= 0 && position <= this.length) { | |
| let node = new LinkNode(element); | |
| let current = this.head; | |
| let previous, index = 0; | |
| while (index++ < position) { | |
| previous = current; | |
| current = current.next; | |
| } | |
| previous.next = node; | |
| node.next = current; | |
| this.length++; | |
| return true; | |
| } else { | |
| return false; | |
| } | |
| } | |
| indexOf(element) { | |
| let current = this.head; | |
| let index = -1; | |
| while (current) { | |
| index++; | |
| if (element === current.element) { | |
| return index; | |
| } | |
| current = current.next; | |
| } | |
| return -1; | |
| } | |
| removeAt(position) { | |
| if (position >= 0 && position < this.length) { | |
| let current = this.head; | |
| let previous; | |
| let index = 0; | |
| if (position === 0) { | |
| this.head = current.next; | |
| } else { | |
| while (index++ < position) { | |
| previous = current; | |
| current = current.next; | |
| } | |
| previous.next = current.next; | |
| } | |
| this.length--; | |
| return current.element; | |
| } else { | |
| return null; | |
| } | |
| } | |
| remove(element) { | |
| let index = this.indexOf(element); | |
| this.removeAt(index); | |
| } | |
| isEmpty() { | |
| return this.length === 0; | |
| } | |
| size() { | |
| return this.length; | |
| } | |
| toString() { | |
| let current = this.head; | |
| let string = ''; | |
| while (current) { | |
| string += current.element + (current.next ? 'n' : ''); | |
| current = current.next; | |
| } | |
| return string; | |
| } | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://github.com/loiane/javascript-datastructures-algorithms