Skip to content

Instantly share code, notes, and snippets.

@primaryobjects
Created December 27, 2023 21:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save primaryobjects/8bb98747d53e5b352a351890e8100b10 to your computer and use it in GitHub Desktop.
Save primaryobjects/8bb98747d53e5b352a351890e8100b10 to your computer and use it in GitHub Desktop.
Design a singly linked list https://neetcode.io/problems/singlyLinkedList
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