Created
December 27, 2023 21:18
-
-
Save primaryobjects/8bb98747d53e5b352a351890e8100b10 to your computer and use it in GitHub Desktop.
Design a singly linked list https://neetcode.io/problems/singlyLinkedList
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(value, next) { | |
this.value = value; | |
this.next = next; | |
} | |
} | |
class LinkedList { | |
constructor() { | |
this.head = null; | |
} | |
/** | |
* @param {number} index | |
* @return {number} | |
*/ | |
get(index) { | |
let i = 0; | |
let current = this.head; | |
while (i++ < index && current) { | |
current = current.next; | |
} | |
return current ? current.value : -1; | |
} | |
/** | |
* @param {number} val | |
* @return {void} | |
*/ | |
insertHead(val) { | |
const node = new Node(val, this.head); | |
this.head = node; | |
} | |
/** | |
* @param {number} val | |
* @return {void} | |
*/ | |
insertTail(val) { | |
let current = this.head; | |
if (!current) { | |
this.head = new Node(val); | |
} | |
else { | |
while (current.next) { | |
current = current.next; | |
} | |
current.next = new Node(val); | |
} | |
} | |
/** | |
* @param {number} index | |
* @return {boolean} | |
*/ | |
remove(index) { | |
let i = 0; | |
let current = this.head; | |
let parent = null; | |
while (i++ < index && current) { | |
parent = current; | |
current = current.next; | |
} | |
if (current) { | |
if (parent) { | |
parent.next = current.next; | |
} | |
else { | |
// Removing the head. | |
this.head = this.head.next; | |
} | |
} | |
return current ? true : false; | |
} | |
/** | |
* @return {number[]} | |
*/ | |
getValues() { | |
const values = []; | |
let current = this.head; | |
while (current) { | |
values.push(current.value); | |
current = current.next; | |
} | |
return values; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment