Created
January 6, 2023 07:23
-
-
Save hansamlin/c24782b66d9e31eef225e17089132ea9 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 LinkedListNode { | |
constructor(value) { | |
this.next = null; | |
this.value = value; | |
} | |
} | |
class LinkedList { | |
constructor() { | |
this.head = null; | |
this.length = 0; | |
} | |
size() { | |
return this.length; | |
} | |
append(value) { | |
const newNode = new LinkedListNode(value); | |
if (this.head === null) { | |
this.head = newNode; | |
} else { | |
let c = this.head; | |
while (c.next !== null) { | |
c = c.next; | |
} | |
c.next = newNode; | |
} | |
this.length += 1; | |
} | |
insert(position, value) { | |
if ((position > this.length - 1 || position < 0) && position !== 0) { | |
return false; | |
} | |
const newNode = new LinkedListNode(value); | |
if (position === 0) { | |
newNode.next = this.head; | |
this.head = newNode; | |
} else { | |
let c = this.head; | |
for (let i = 1; i < position; i += 1) { | |
c = c.next; | |
} | |
newNode.next = c.next; | |
c.next = newNode; | |
} | |
this.length += 1; | |
return true; | |
} | |
remove(value) { | |
// let c = this.head; | |
// let prev; | |
// while (c.value !== value) { | |
// prev = c; | |
// c = c.next; | |
// } | |
// prev.next = c.next; | |
// this.length -= 1; | |
const index = this.indexOf(value); | |
return this.removeAt(index); | |
} | |
removeAt(position) { | |
if (position > this.length - 1 || position < 0) return false; | |
if (position === 0) { | |
this.head = this.head.next; | |
} else { | |
let c = this.head; | |
for (let i = 1; i < position; i += 1) { | |
c = c.next; | |
} | |
c.next = c.next.next; | |
} | |
this.length -= 1; | |
return true; | |
} | |
indexOf(value) { | |
if (this.length === 0) return -1; | |
let i = 0; | |
let c = this.head; | |
while (c !== null) { | |
if (c.value === value) { | |
return i; | |
} | |
i += 1; | |
c = c.next; | |
} | |
return -1; | |
} | |
toString() { | |
return JSON.stringify(this, null, 4); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment