trie-typed
Version:
Trie, prefix tree
452 lines (451 loc) • 19.5 kB
TypeScript
/**
* data-structure-typed
*
* @author Pablo Zeng
* @copyright Copyright (c) 2022 Pablo Zeng <zrwusa@gmail.com>
* @license MIT License
*/
import type { ElementCallback, SinglyLinkedListOptions } from '../../types';
import { LinearLinkedBase, LinkedListNode } from '../base/linear-base';
/**
* Node of a singly linked list; stores value and the next link.
* @remarks Time O(1), Space O(1)
* @template E
*/
export declare class SinglyLinkedListNode<E = any> extends LinkedListNode<E> {
/**
* Create a list node.
* @remarks Time O(1), Space O(1)
* @param value - Element value to store.
* @returns New node instance.
*/
constructor(value: E);
protected _next: SinglyLinkedListNode<E> | undefined;
/**
* Get the next node.
* @remarks Time O(1), Space O(1)
* @returns Next node or undefined.
*/
get next(): SinglyLinkedListNode<E> | undefined;
/**
* Set the next node.
* @remarks Time O(1), Space O(1)
* @param value - Next node or undefined.
* @returns void
*/
set next(value: SinglyLinkedListNode<E> | undefined);
}
/**
* Singly linked list with O(1) push/pop-like ends operations and linear scans.
* @remarks Time O(1), Space O(1)
* @template E
* @template R
* 1. Node Structure: Each node contains three parts: a data field, a pointer (or reference) to the previous node, and a pointer to the next node. This structure allows traversal of the linked list in both directions.
* 2. Bidirectional Traversal: Unlike doubly linked lists, singly linked lists can be easily traversed forwards but not backwards.
* 3. No Centralized Index: Unlike arrays, elements in a linked list are not stored contiguously, so there is no centralized index. Accessing elements in a linked list typically requires traversing from the head or tail node.
* 4. High Efficiency in Insertion and Deletion: Adding or removing elements in a linked list does not require moving other elements, making these operations more efficient than in arrays.
* Caution: Although our linked list classes provide methods such as at, setAt, addAt, and indexOf that are based on array indices, their time complexity, like that of the native Array.lastIndexOf, is 𝑂(𝑛). If you need to use these methods frequently, you might want to consider other data structures, such as Deque or Queue (designed for random access). Similarly, since the native Array.shift method has a time complexity of 𝑂(𝑛), using an array to simulate a queue can be inefficient. In such cases, you should use Queue or Deque, as these data structures leverage deferred array rearrangement, effectively reducing the average time complexity to 𝑂(1).
* @example
* // implementation of a basic text editor
* class TextEditor {
* private content: SinglyLinkedList<string>;
* private cursorIndex: number;
* private undoStack: Stack<{ operation: string; data?: any }>;
*
* constructor() {
* this.content = new SinglyLinkedList<string>();
* this.cursorIndex = 0; // Cursor starts at the beginning
* this.undoStack = new Stack<{ operation: string; data?: any }>(); // Stack to keep track of operations for undo
* }
*
* insert(char: string) {
* this.content.addAt(this.cursorIndex, char);
* this.cursorIndex++;
* this.undoStack.push({ operation: 'insert', data: { index: this.cursorIndex - 1 } });
* }
*
* delete() {
* if (this.cursorIndex === 0) return; // Nothing to delete
* const deleted = this.content.deleteAt(this.cursorIndex - 1);
* this.cursorIndex--;
* this.undoStack.push({ operation: 'delete', data: { index: this.cursorIndex, char: deleted } });
* }
*
* moveCursor(index: number) {
* this.cursorIndex = Math.max(0, Math.min(index, this.content.length));
* }
*
* undo() {
* if (this.undoStack.size === 0) return; // No operations to undo
* const lastAction = this.undoStack.pop();
*
* if (lastAction!.operation === 'insert') {
* this.content.deleteAt(lastAction!.data.index);
* this.cursorIndex = lastAction!.data.index;
* } else if (lastAction!.operation === 'delete') {
* this.content.addAt(lastAction!.data.index, lastAction!.data.char);
* this.cursorIndex = lastAction!.data.index + 1;
* }
* }
*
* getText(): string {
* return [...this.content].join('');
* }
* }
*
* // Example Usage
* const editor = new TextEditor();
* editor.insert('H');
* editor.insert('e');
* editor.insert('l');
* editor.insert('l');
* editor.insert('o');
* console.log(editor.getText()); // 'Hello' // Output: "Hello"
*
* editor.delete();
* console.log(editor.getText()); // 'Hell' // Output: "Hell"
*
* editor.undo();
* console.log(editor.getText()); // 'Hello' // Output: "Hello"
*
* editor.moveCursor(1);
* editor.insert('a');
* console.log(editor.getText()); // 'Haello'
*/
export declare class SinglyLinkedList<E = any, R = any> extends LinearLinkedBase<E, R, SinglyLinkedListNode<E>> {
protected _equals: (a: E, b: E) => boolean;
/**
* Create a SinglyLinkedList and optionally bulk-insert elements.
* @remarks Time O(N), Space O(N)
* @param [elements] - Iterable of elements or nodes (or raw records if toElementFn is provided).
* @param [options] - Options such as maxLen and toElementFn.
* @returns New SinglyLinkedList instance.
*/
constructor(elements?: Iterable<E> | Iterable<R> | Iterable<SinglyLinkedListNode<E>>, options?: SinglyLinkedListOptions<E, R>);
protected _head: SinglyLinkedListNode<E> | undefined;
/**
* Get the head node.
* @remarks Time O(1), Space O(1)
* @returns Head node or undefined.
*/
get head(): SinglyLinkedListNode<E> | undefined;
protected _tail: SinglyLinkedListNode<E> | undefined;
/**
* Get the tail node.
* @remarks Time O(1), Space O(1)
* @returns Tail node or undefined.
*/
get tail(): SinglyLinkedListNode<E> | undefined;
protected _length: number;
/**
* Get the number of elements.
* @remarks Time O(1), Space O(1)
* @returns Current length.
*/
get length(): number;
/**
* Get the first element value.
* @remarks Time O(1), Space O(1)
* @returns First element or undefined.
*/
get first(): E | undefined;
/**
* Get the last element value.
* @remarks Time O(1), Space O(1)
* @returns Last element or undefined.
*/
get last(): E | undefined;
/**
* Create a new list from an iterable of elements.
* @remarks Time O(N), Space O(N)
* @template E
* @template R
* @template S
* @param this - The constructor (subclass) to instantiate.
* @param data - Iterable of elements to insert.
* @param [options] - Options forwarded to the constructor.
* @returns A new list populated with the iterable's elements.
*/
static from<E, R = any, S extends SinglyLinkedList<E, R> = SinglyLinkedList<E, R>>(this: new (elements?: Iterable<E> | Iterable<R> | Iterable<SinglyLinkedListNode<E>>, options?: SinglyLinkedListOptions<E, R>) => S, data: Iterable<E>, options?: SinglyLinkedListOptions<E, R>): S;
/**
* Append an element/node to the tail.
* @remarks Time O(1), Space O(1)
* @param elementOrNode - Element or node to append.
* @returns True when appended.
*/
push(elementOrNode: E | SinglyLinkedListNode<E>): boolean;
/**
* Remove and return the tail element.
* @remarks Time O(N), Space O(1)
* @returns Removed element or undefined.
*/
pop(): E | undefined;
/**
* Remove and return the head element.
* @remarks Time O(1), Space O(1)
* @returns Removed element or undefined.
*/
shift(): E | undefined;
/**
* Prepend an element/node to the head.
* @remarks Time O(1), Space O(1)
* @param elementOrNode - Element or node to prepend.
* @returns True when prepended.
*/
unshift(elementOrNode: E | SinglyLinkedListNode<E>): boolean;
/**
* Append a sequence of elements/nodes.
* @remarks Time O(N), Space O(1)
* @param elements - Iterable of elements or nodes (or raw records if toElementFn is provided).
* @returns Array of per-element success flags.
*/
pushMany(elements: Iterable<E> | Iterable<R> | Iterable<SinglyLinkedListNode<E>>): boolean[];
/**
* Prepend a sequence of elements/nodes.
* @remarks Time O(N), Space O(1)
* @param elements - Iterable of elements or nodes (or raw records if toElementFn is provided).
* @returns Array of per-element success flags.
*/
unshiftMany(elements: Iterable<E> | Iterable<R> | Iterable<SinglyLinkedListNode<E>>): boolean[];
/**
* Find the first value matching a predicate (by node).
* @remarks Time O(N), Space O(1)
* @param elementNodeOrPredicate - Element, node, or node predicate to match.
* @returns Matched value or undefined.
*/
search(elementNodeOrPredicate: E | SinglyLinkedListNode<E> | ((node: SinglyLinkedListNode<E>) => boolean)): E | undefined;
/**
* Get the element at a given index.
* @remarks Time O(N), Space O(1)
* @param index - Zero-based index.
* @returns Element or undefined.
*/
at(index: number): E | undefined;
/**
* Type guard: check whether the input is a SinglyLinkedListNode.
* @remarks Time O(1), Space O(1)
* @param elementNodeOrPredicate - Element, node, or predicate.
* @returns True if the value is a SinglyLinkedListNode.
*/
isNode(elementNodeOrPredicate: E | SinglyLinkedListNode<E> | ((node: SinglyLinkedListNode<E>) => boolean)): elementNodeOrPredicate is SinglyLinkedListNode<E>;
/**
* Get the node reference at a given index.
* @remarks Time O(N), Space O(1)
* @param index - Zero-based index.
* @returns Node or undefined.
*/
getNodeAt(index: number): SinglyLinkedListNode<E> | undefined;
/**
* Delete the element at an index.
* @remarks Time O(N), Space O(1)
* @param index - Zero-based index.
* @returns Removed element or undefined.
*/
deleteAt(index: number): E | undefined;
/**
* Delete the first match by value/node.
* @remarks Time O(N), Space O(1)
* @param [elementOrNode] - Element or node to remove; if omitted/undefined, nothing happens.
* @returns True if removed.
*/
delete(elementOrNode: E | SinglyLinkedListNode<E> | undefined): boolean;
/**
* Insert a new element/node at an index, shifting following nodes.
* @remarks Time O(N), Space O(1)
* @param index - Zero-based index.
* @param newElementOrNode - Element or node to insert.
* @returns True if inserted.
*/
addAt(index: number, newElementOrNode: E | SinglyLinkedListNode<E>): boolean;
/**
* Set the element value at an index.
* @remarks Time O(N), Space O(1)
* @param index - Zero-based index.
* @param value - New value.
* @returns True if updated.
*/
setAt(index: number, value: E): boolean;
/**
* Check whether the list is empty.
* @remarks Time O(1), Space O(1)
* @returns True if length is 0.
*/
isEmpty(): boolean;
/**
* Remove all nodes and reset length.
* @remarks Time O(N), Space O(1)
* @returns void
*/
clear(): void;
/**
* Reverse the list in place.
* @remarks Time O(N), Space O(1)
* @returns This list.
*/
reverse(): this;
/**
* Find a node by value, reference, or predicate.
* @remarks Time O(N), Space O(1)
* @param [elementNodeOrPredicate] - Element, node, or node predicate to match.
* @returns Matching node or undefined.
*/
getNode(elementNodeOrPredicate: E | SinglyLinkedListNode<E> | ((node: SinglyLinkedListNode<E>) => boolean) | undefined): SinglyLinkedListNode<E> | undefined;
/**
* Insert a new element/node before an existing one.
* @remarks Time O(N), Space O(1)
* @param existingElementOrNode - Existing element or node.
* @param newElementOrNode - Element or node to insert.
* @returns True if inserted.
*/
addBefore(existingElementOrNode: E | SinglyLinkedListNode<E>, newElementOrNode: E | SinglyLinkedListNode<E>): boolean;
/**
* Insert a new element/node after an existing one.
* @remarks Time O(N), Space O(1)
* @param existingElementOrNode - Existing element or node.
* @param newElementOrNode - Element or node to insert.
* @returns True if inserted.
*/
addAfter(existingElementOrNode: E | SinglyLinkedListNode<E>, newElementOrNode: E | SinglyLinkedListNode<E>): boolean;
/**
* Remove and/or insert elements at a position (array-like behavior).
* @remarks Time O(N + M), Space O(M)
* @param start - Start index (clamped to [0, length]).
* @param [deleteCount] - Number of elements to remove (default 0).
* @param [items] - Elements to insert after `start`.
* @returns A new list containing the removed elements (typed as `this`).
*/
splice(start: number, deleteCount?: number, ...items: E[]): this;
/**
* Count how many nodes match a value/node/predicate.
* @remarks Time O(N), Space O(1)
* @param elementOrNode - Element, node, or node predicate to match.
* @returns Number of matches in the list.
*/
countOccurrences(elementOrNode: E | SinglyLinkedListNode<E> | ((node: SinglyLinkedListNode<E>) => boolean)): number;
/**
* Set the equality comparator used to compare values.
* @remarks Time O(1), Space O(1)
* @param equals - Equality predicate (a, b) → boolean.
* @returns This list.
*/
setEquality(equals: (a: E, b: E) => boolean): this;
/**
* Delete the first node whose value matches a predicate.
* @remarks Time O(N), Space O(1)
* @param predicate - Predicate (value, index, list) → boolean to decide deletion.
* @returns True if a node was removed.
*/
deleteWhere(predicate: (value: E, index: number, list: this) => boolean): boolean;
/**
* Deep clone this list (values are copied by reference).
* @remarks Time O(N), Space O(N)
* @returns A new list with the same element sequence.
*/
clone(): this;
/**
* Filter values into a new list of the same class.
* @remarks Time O(N), Space O(N)
* @param callback - Predicate (value, index, list) → boolean to keep value.
* @param [thisArg] - Value for `this` inside the callback.
* @returns A new list with kept values.
*/
filter(callback: ElementCallback<E, R, boolean>, thisArg?: any): this;
/**
* Map values into a new list of the same class.
* @remarks Time O(N), Space O(N)
* @param callback - Mapping function (value, index, list) → newValue.
* @param [thisArg] - Value for `this` inside the callback.
* @returns A new list with mapped values.
*/
mapSame(callback: ElementCallback<E, R, E>, thisArg?: any): this;
/**
* Map values into a new list (possibly different element type).
* @remarks Time O(N), Space O(N)
* @template EM
* @template RM
* @param callback - Mapping function (value, index, list) → newElement.
* @param [options] - Options for the output list (e.g., maxLen, toElementFn).
* @param [thisArg] - Value for `this` inside the callback.
* @returns A new SinglyLinkedList with mapped values.
*/
map<EM, RM = any>(callback: ElementCallback<E, R, EM>, options?: SinglyLinkedListOptions<EM, RM>, thisArg?: any): SinglyLinkedList<EM, RM>;
/**
* (Protected) Create a node from a value.
* @remarks Time O(1), Space O(1)
* @param value - Value to wrap in a node.
* @returns A new SinglyLinkedListNode instance.
*/
protected _createNode(value: E): SinglyLinkedListNode<E>;
/**
* (Protected) Check if input is a node predicate function.
* @remarks Time O(1), Space O(1)
* @param elementNodeOrPredicate - Element, node, or node predicate.
* @returns True if input is a predicate function.
*/
protected _isPredicate(elementNodeOrPredicate: E | SinglyLinkedListNode<E> | ((node: SinglyLinkedListNode<E>) => boolean)): elementNodeOrPredicate is (node: SinglyLinkedListNode<E>) => boolean;
/**
* (Protected) Normalize input into a node instance.
* @remarks Time O(1), Space O(1)
* @param elementOrNode - Element or node.
* @returns A SinglyLinkedListNode for the provided input.
*/
protected _ensureNode(elementOrNode: E | SinglyLinkedListNode<E>): SinglyLinkedListNode<E>;
/**
* (Protected) Normalize input into a node predicate.
* @remarks Time O(1), Space O(1)
* @param elementNodeOrPredicate - Element, node, or predicate.
* @returns A predicate taking a node and returning true/false.
*/
protected _ensurePredicate(elementNodeOrPredicate: E | SinglyLinkedListNode<E> | ((node: SinglyLinkedListNode<E>) => boolean)): (node: SinglyLinkedListNode<E>) => boolean;
/**
* (Protected) Get the previous node of a given node.
* @remarks Time O(N), Space O(1)
* @param node - A node in the list.
* @returns Previous node or undefined.
*/
protected _getPrevNode(node: SinglyLinkedListNode<E>): SinglyLinkedListNode<E> | undefined;
/**
* (Protected) Iterate values from head to tail.
* @remarks Time O(N), Space O(1)
* @returns Iterator of values (E).
*/
protected _getIterator(): IterableIterator<E>;
/**
* (Protected) Iterate values from tail to head.
* @remarks Time O(N), Space O(N)
* @returns Iterator of values (E).
*/
protected _getReverseIterator(): IterableIterator<E>;
/**
* (Protected) Iterate nodes from head to tail.
* @remarks Time O(N), Space O(1)
* @returns Iterator of nodes.
*/
protected _getNodeIterator(): IterableIterator<SinglyLinkedListNode<E>>;
/**
* (Protected) Create an empty instance of the same concrete class.
* @remarks Time O(1), Space O(1)
* @param [options] - Options forwarded to the constructor.
* @returns An empty like-kind list instance.
*/
protected _createInstance(options?: SinglyLinkedListOptions<E, R>): this;
/**
* (Protected) Create a like-kind instance and seed it from an iterable.
* @remarks Time O(N), Space O(N)
* @template EM
* @template RM
* @param [elements] - Iterable used to seed the new list.
* @param [options] - Options forwarded to the constructor.
* @returns A like-kind SinglyLinkedList instance.
*/
protected _createLike<EM, RM>(elements?: Iterable<EM> | Iterable<RM> | Iterable<SinglyLinkedListNode<EM>>, options?: SinglyLinkedListOptions<EM, RM>): SinglyLinkedList<EM, RM>;
/**
* (Protected) Spawn an empty like-kind list instance.
* @remarks Time O(1), Space O(1)
* @template EM
* @template RM
* @param [options] - Options forwarded to the constructor.
* @returns An empty like-kind SinglyLinkedList instance.
*/
protected _spawnLike<EM, RM>(options?: SinglyLinkedListOptions<EM, RM>): SinglyLinkedList<EM, RM>;
}