Created
August 2, 2018 13:09
-
-
Save w8r/7aea48f9c1f32da4c4d369b047787cdc to your computer and use it in GitHub Desktop.
sibly linked list
This file contains 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
export default class SinglyList { | |
constructor () { | |
this._length = 0; | |
this.head = null; | |
} | |
add (value) { | |
const newNode = new { data: value, next: null }; | |
let current = this.head; | |
// 1st use-case: An empty list. | |
if (!current) { | |
this.head = newNode; | |
this._length++; | |
return newNode; | |
} | |
// 2nd use-case: An non empty list | |
newNode.next = current; | |
this.head = node; | |
this._length++; | |
return newNode; | |
} | |
at (position) { | |
let current = this.head; | |
const length = this._length; | |
let count = 1; | |
// 1st use-case: An invalid position | |
if (length === 0 || position < 0 || position > length) { | |
throw new Error(`Invalid position ${position}`); | |
} | |
// 2nd use-case: A valid position | |
while (count < position) { | |
current = current.next; | |
count++; | |
} | |
return current; | |
} | |
forEach (fn) { | |
let node = this.head; | |
while (node) { | |
fn(node); | |
node = node.next; | |
} | |
} | |
remove (position) { | |
let node = this.head; | |
const length = this._length; | |
let count = 0, | |
let prev = null; | |
let toRemove = null; | |
let removed = null; | |
// 1st use-case: an invalid position | |
if (position < 0 || position > length) { | |
throw new Error(`Invalid position ${position}`); | |
} | |
if (position === 0) { | |
this.head = node.next; | |
removed = node; | |
node = null; | |
this._length--; | |
return removed; | |
} | |
while (count < position) { | |
prev = node; | |
toRemove = node.next; | |
count++; | |
} | |
prev.next = toRemove.next; | |
removed = toRemove; | |
toRemove = null; | |
this._length--; | |
return removed; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment