Created
November 12, 2023 22:50
-
-
Save shadeemerhi/8e476cbed8ffd527e363ac98ceb6e687 to your computer and use it in GitHub Desktop.
Design a Singly Linked List
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 ListNode { | |
constructor(val) { | |
this.val = val; | |
this.next = null; | |
} | |
} | |
class LinkedList { | |
constructor() { | |
this.head = null; | |
this.tail = this.head; | |
} | |
/** | |
* @param {number} index | |
* @return {number} | |
*/ | |
get(index) { | |
let currentNode = this.head; | |
let currentIndex = 0; | |
while(currentNode) { | |
if (currentIndex === index) { | |
return currentNode.val; | |
} | |
currentNode = currentNode.next; | |
currentIndex++; | |
} | |
return -1; | |
} | |
/** | |
* @param {number} val | |
* @return {void} | |
*/ | |
insertHead(val) { | |
const newNode = new ListNode(val); | |
newNode.next = this.head; | |
this.head = newNode; | |
// List was empty | |
if (!newNode.next) { | |
this.tail = newNode; | |
} | |
} | |
/** | |
* @param {number} val | |
* @return {void} | |
*/ | |
insertTail(val) { | |
const newNode = new ListNode(val); | |
// Empty list | |
if (!this.head) { | |
this.head = newNode; | |
this.tail = this.head; | |
} | |
else { | |
this.tail.next = newNode; | |
this.tail = newNode; | |
} | |
} | |
/** | |
* @param {number} index | |
* @return {boolean} | |
*/ | |
remove(index) { | |
let i = 0; | |
let curr = this.head; | |
// Removing head case | |
if (index === 0 && this.head) { | |
this.head = this.head.next; | |
return true; | |
} | |
while (i < index - 1 && curr) { | |
i++; | |
curr = curr.next; | |
} | |
// Remove the node ahead of curr | |
if (curr && curr.next) { | |
if (curr.next === this.tail) { | |
this.tail = curr; | |
} | |
curr.next = curr.next.next; | |
return true; | |
} | |
return false; | |
} | |
/** | |
* @return {number[]} | |
*/ | |
getValues() { | |
let currentNode = this.head; | |
const values = []; | |
while (currentNode) { | |
values.push(currentNode.val); | |
currentNode = currentNode.next; | |
} | |
return values; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment