MST

星途 面试题库

面试题:TypeScript迭代器在自定义数据结构中的应用

假设你正在实现一个自定义的链表数据结构,在TypeScript中如何运用迭代器模式,使得这个链表能够被方便地遍历?请给出链表节点的定义、链表类的实现以及迭代器相关的代码。
28.8万 热度难度
前端开发TypeScript

知识考点

AI 面试

面试题答案

一键面试
// 链表节点定义
class ListNode<T> {
    value: T;
    next: ListNode<T> | null;
    constructor(value: T) {
        this.value = value;
        this.next = null;
    }
}

// 链表类实现
class LinkedList<T> {
    private head: ListNode<T> | null;
    constructor() {
        this.head = null;
    }

    add(value: T) {
        const newNode = new ListNode(value);
        if (!this.head) {
            this.head = newNode;
        } else {
            let current = this.head;
            while (current.next) {
                current = current.next;
            }
            current.next = newNode;
        }
    }

    // 迭代器相关代码
    [Symbol.iterator](): Iterator<T> {
        let current = this.head;
        return {
            next(): IteratorResult<T> {
                if (current) {
                    const value = current.value;
                    current = current.next;
                    return { value, done: false };
                }
                return { value: undefined, done: true };
            }
        };
    }
}

可以这样使用:

const list = new LinkedList<number>();
list.add(1);
list.add(2);
list.add(3);

for (const num of list) {
    console.log(num);
}