Generic singly linked list with common operations
class ListNode<T> {
data: T;
next: ListNode<T> | null;
constructor(data: T) {
this.data = data;
this.next = null;
}
}
class LinkedList<T> {
private head: ListNode<T> | null;
private size: number;
constructor() {
this.head = null;
this.size = 0;
}
// Add element to the beginning
prepend(data: T): void {
const newNode = new ListNode(data);
newNode.next = this.head;
this.head = newNode;
this.size++;
}
// Add element to the end
append(data: T): void {
const newNode = new ListNode(data);
if (!this.head) {
this.head = newNode;
} else {
let current = this.head;
while (current.next) {
current = current.next;
}
current.next = newNode;
}
this.size++;
}
// Remove element by value
remove(data: T): boolean {
if (!this.head) return false;
if (this.head.data === data) {
this.head = this.head.next;
this.size--;
return true;
}
let current = this.head;
while (current.next && current.next.data !== data) {
current = current.next;
}
if (current.next) {
current.next = current.next.next;
this.size--;
return true;
}
return false;
}
// Find element
find(data: T): ListNode<T> | null {
let current = this.head;
while (current) {
if (current.data === data) {
return current;
}
current = current.next;
}
return null;
}
// Get size
getSize(): number {
return this.size;
}
// Convert to array
toArray(): T[] {
const result: T[] = [];
let current = this.head;
while (current) {
result.push(current.data);
current = current.next;
}
return result;
}
}
// Example usage
const list = new LinkedList<number>();
list.append(1);
list.append(2);
list.append(3);
list.prepend(0);
console.log("List:", list.toArray()); // [0, 1, 2, 3]
console.log("Size:", list.getSize()); // 4
list.remove(2);
console.log("After removing 2:", list.toArray()); // [0, 1, 3]
Views
Lines
Characters
Likes