Created
January 27, 2019 10:02
-
-
Save hk-skit/64cfa31783f7e92821d7b05edc5463cd 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 Node { | |
constructor(value) { | |
this.value = value; | |
this.next = null; | |
} | |
} | |
class LinkedList { | |
constructor() { | |
this.head = null; | |
this.tail = null; | |
} | |
get isEmpty() { | |
return this.head === null; | |
} | |
add(value) { | |
const node = new Node(value); | |
if (this.head === null) { | |
this.head = this.tail = node; | |
return this; | |
} | |
this.tail.next = node; | |
this.tail = node; | |
return this; | |
} | |
addHead(value) { | |
const node = new Node(value); | |
node.next = this.head; | |
this.head = node; | |
} | |
removeHead() { | |
if (this.isEmpty) { | |
return null; | |
} | |
const head = this.head; | |
this.head = this.head.next; | |
return head.value; | |
} | |
removeTail() { | |
if (this.isEmpty) { | |
return null; | |
} | |
const { | |
value | |
} = this.tail; | |
if (this.head === this.tail) { | |
// List with single node. | |
this.tail = this.head = null; | |
return value; | |
} | |
let prev = null; | |
let current = this.head; | |
while (current.next !== null) { | |
prev = current; | |
current = current.next; | |
} | |
// Adjust tail pointer. | |
prev.next = null; | |
this.tail = prev; | |
return value; | |
} | |
remove(x) { | |
let prev = null; | |
let current = this.head; | |
while (current !== null) { | |
const { | |
value, | |
next | |
} = current; | |
if (value !== x) { | |
prev = current; | |
current = next; | |
continue; | |
} | |
// If value is at head. | |
if (prev === null) { | |
this.head = next; | |
} else { | |
prev.next = next; | |
} | |
return x; | |
} | |
return null; | |
} | |
} | |
const list = [2, 1, 3, 4, 5].reduce((list, value) => | |
list.add(value), new LinkedList()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment