@utilityjs/linked-list
v2.0.0
Published
An implementation of LinkedList data structure.
Maintainers
Readme
UtilityJS | Linked List
A singly linked list data structure implementation.
Features
- Singly Linked: Efficient head and tail operations
- Custom Comparator: Support for custom element comparison
- Traversal: Iterate through nodes with callback
- Array Conversion: Convert to and from arrays
Installation
npm install @utilityjs/linked-listor
pnpm add @utilityjs/linked-listUsage
Basic Usage
import { LinkedList } from "@utilityjs/linked-list";
const list = new LinkedList<number>();
list.append(1);
list.append(2);
list.prepend(0);
list.toArray(); // [0, 1, 2]Traversal
list.traverse((node, index) => {
console.log(`Index ${index}: ${node.getValue()}`);
});Custom Comparator
import { LinkedList } from "@utilityjs/linked-list";
interface Item {
id: number;
value: string;
}
const list = new LinkedList<Item>((a, b) => {
if (a.id === b.id) return 0;
return a.id < b.id ? -1 : 1;
});
list.append({ id: 1, value: "first" });
list.append({ id: 2, value: "second" });
list.delete({ id: 1, value: "first" });API
LinkedList<T>
Constructor
new LinkedList<T>(compareFunction?: CompareFunction<T>)- Creates a list with optional comparator
Methods
getHead(): Node<T> | null- Get the head nodegetTail(): Node<T> | null- Get the tail nodeisEmpty(): boolean- Check if the list is emptygetLength(): number- Get the number of elementsappend(value: T): void- Add element to the endprepend(value: T): void- Add element to the beginningtraverse(callback: (node, index) => void | boolean): void- Iterate through nodesdeleteHead(): void- Remove the first elementdeleteTail(): void- Remove the last elementdelete(value: T): void- Remove first occurrence of valuereverse(): void- Reverse the list orderfromArray(array: T[]): void- Populate from an arraytoArray(): T[]- Convert to an array
Contributing
Read the contributing guide to learn about our development process, how to propose bug fixes and improvements, and how to build and test your changes.
License
This project is licensed under the terms of the MIT license.
