Last active
August 3, 2024 08:18
-
-
Save gofer/f78f99440e7ee68e6349bb34f5939a9e to your computer and use it in GitHub Desktop.
Linked List
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 = null, next = null) { | |
this.value = value; | |
this.next = next; | |
} | |
} | |
class List { | |
constructor() { | |
this.head = null; | |
this.tail = null; | |
this.length = 0; | |
} | |
append(value) { | |
const newNode = new Node(value); | |
if (!this.head) { | |
this.head = newNode; | |
this.tail = this.head; | |
} else { | |
this.tail.next = newNode; | |
this.tail = newNode; | |
} | |
++this.length; | |
return this; | |
} | |
prepend(value) { | |
const newNode = new Node(value, this.head); | |
if (!this.head) { | |
this.tail = newNode; | |
} | |
this.head = newNode; | |
++this.length; | |
return this; | |
} | |
pop() { | |
if (!this.head) { | |
return null; | |
} | |
let node = this.head; | |
let prev = null; | |
while (node.next) { | |
prev = node; | |
node = node.next; | |
} | |
const value = node.value; | |
this.tail = prev; | |
if (prev) { | |
prev.next = null; | |
} else { | |
this.head = null; | |
} | |
--this.length; | |
return value; | |
} | |
shift() { | |
if (!this.head) { | |
return null; | |
} | |
const value = this.head.value; | |
this.head = this.head.next; | |
if (!this.head) { | |
this.tail = null; | |
} | |
--this.length; | |
return value; | |
} | |
insert(index, value) { | |
if (index < -1 || this.length <= index) { | |
return this; | |
} | |
if (!this.head || index == -1) { | |
return this.prepend(value); | |
} | |
let node = this.head; | |
while (index > 0) { | |
node = node.next; | |
--index; | |
} | |
const newNode = new Node(value, node.next); | |
node.next = newNode; | |
++this.length; | |
return this; | |
} | |
remove(index) { | |
if (!this.head || index < 0 || this.length <= index) { | |
return null; | |
} | |
--index; | |
if (index < 0) { | |
this.shift(); | |
return this; | |
} | |
let node = this.head; | |
while (index > 0) { | |
node = node.next; | |
--index; | |
} | |
if (node.next == this.tail) { | |
this.tail = node; | |
} | |
node.next = node.next.next; | |
--this.length; | |
return node; | |
} | |
to_array() { | |
const array = []; | |
let node = this.head; | |
while (node) { | |
array.push(node.value); | |
node = node.next; | |
} | |
return array; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment