Developed and Maintained by Hemant
This implementation demonstrates how to create and manage a singly linked list using TypeScript. It covers the core functionalities such as inserting nodes, deleting nodes, searching for elements, and traversing the list. The code emphasizes type safety, modular design, and clarity, making it ideal for beginners and intermediate developers looking to strengthen their understanding of data structures in a strongly-typed JavaScript environment.
// Node class
class ListNode<T> {
value: T;
next: ListNode<T> | null = null;
constructor(value: T) {
this.value = value;
}
}
// LinkedList class
class LinkedList<T> {
private head: ListNode<T> | null = null;
// Insert at end
append(value: T): void {
const newNode = new ListNode(value);
if (!this.head) {
this.head = newNode;
return;
}
let current = this.head;
while (current.next) {
current = current.next;
}
current.next = newNode;
}
// Insert at beginning
prepend(value: T): void {
const newNode = new ListNode(value);
newNode.next = this.head;
this.head = newNode;
}
// Delete first occurrence of value
delete(value: T): void {
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;
}
}
// Find a node by value
find(value: T): ListNode<T> | null {
let current = this.head;
while (current) {
if (current.value === value) return current;
current = current.next;
}
return null;
}
// Print list of Elemets
print(): void {
let current = this.head;
const values: T[] = [];
while (current) {
values.push(current.value);
current = current.next;
}
console.log(values.join(" -> "));
}
}