Last active
October 18, 2016 07:07
-
-
Save tcstory/a7c1e1d9f8ec222539d4bd0e60d9dd43 to your computer and use it in GitHub Desktop.
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
class Node { | |
constructor(element) { | |
this.element = element; | |
this.next = null; | |
} | |
} | |
class LinkedList { | |
constructor() { | |
this._length = 0; | |
this._head = null; | |
} | |
append(element) { | |
let node = new Node(element); | |
let current; | |
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) { | |
let node = new Node(element); | |
if (position > -1 && position <= this._length) { | |
let current = this._head, index = 0, previous; | |
if (position === 0) { | |
node.next = current; | |
this._head = node; | |
} else { | |
while (index < position) { | |
previous = current; | |
current = current.next; | |
index++; | |
} | |
previous.next = node; | |
node.next = current; | |
} | |
this._length++; | |
return true; | |
} else { | |
return false; | |
} | |
} | |
remove(element) { | |
let index = this.indexOf(element); | |
return this.removeAt(index); | |
} | |
removeAt(position) { | |
if (position > -1 && position < this._length) { | |
let current = this._head, index = 0, previous; | |
if (position === 0) { | |
this._head = current.next; | |
} else { | |
while (index < position) { | |
previous = current; | |
current = current.next; | |
index++; | |
} | |
previous.next = current.next; | |
} | |
this._length--; | |
return current.element; | |
} else { | |
return null; | |
} | |
} | |
indexOf(element) { | |
let current = this._head, index = 0; | |
while (current) { | |
if (current.element === element) { | |
return index; | |
} | |
index++; | |
current = current.next; | |
} | |
return -1; | |
} | |
isEmpty() { | |
return this._length === 0; | |
} | |
get size() { | |
return this._length; | |
} | |
getHead() { | |
return this._head; | |
} | |
print() { | |
} | |
toString() { | |
let str = '', current = this._head; | |
while (current) { | |
str += current.element; | |
current = current.next; | |
} | |
return str; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment