Created
March 5, 2018 12:46
-
-
Save kjlape/7ca3b050c019a6b8a334dcbcda580766 to your computer and use it in GitHub Desktop.
Linked List in JS
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
| function Node(data, { left, right } = {}) { | |
| this.data = data | |
| this._left = left || this, | |
| this._right = right || this | |
| } | |
| Node.prototype = { | |
| left, | |
| right, | |
| insertLeft, | |
| insertRight, | |
| remove, | |
| toArray | |
| } | |
| function left() { | |
| return this._left | |
| } | |
| function right() { | |
| return this._right | |
| } | |
| function insertLeft(data) { | |
| const left = new Node(data, { left: this.left(), right: this }) | |
| this._left._right = left | |
| return this._left = left | |
| } | |
| function insertRight(data) { | |
| const right = new Node(data, { left: this, right: this.right() }) | |
| this._right._left = right | |
| return this._right = right | |
| } | |
| function remove() { | |
| this._left._right = this._right | |
| this._right._left = this._left | |
| return this | |
| } | |
| function toArray(direction = 'right') { | |
| const array = [this.data] | |
| let node = this | |
| while (this !== (node = node[direction]())) { | |
| array.push(node.data) | |
| } | |
| return array | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment