UNPKG

js-dsa-utils

Version:

Basic DSA utilities (sorting, searching, stack, queue,linked list etc.)

68 lines (60 loc) 1.34 kB
class Node { constructor(value) { this.value = value; this.next = null; } } class SinglyLinkedList { constructor() { this.head = null; } insertAtHead(value) { const newNode = new Node(value); newNode.next = this.head; this.head = newNode; } insertAtTail(value) { const newNode = new Node(value); if (!this.head) { this.head = newNode; return; } let current = this.head; while (current.next) { current = current.next; } current.next = newNode; } delete(value) { if (!this.head) return; if (this.head.value === value) { this.head = this.head.next; return; } let current = this.head; while (current.next && current.next.value !== value) { current = current.next; } if (current.next) { current.next = current.next.next; } } search(value) { let current = this.head; while (current) { if (current.value === value) return true; current = current.next; } return false; } toArray() { const result = []; let current = this.head; while (current) { result.push(current.value); current = current.next; } return result; } } module.exports = { SinglyLinkedList };