Skip to content

一、节点定义

typescript
class ListNode {
    public val: number;
    public next: ListNode | null;
    constructor(val?: number, next?: ListNode | null) {
        this.val = val === undefined ? 0 : val;
        this.next = next === undefined ? null : next;
    }
}


export default ListNode;

二、链表实现

typescript
import ListNode from "./ListNode";

class SinglyLinkedList {
    public head: ListNode | null; // 指向头结点
    public length: number; // 链表长度
    constructor() {
        this.head = null;
        this.length = 0;
    }

    /**
     * 给链表追加节点
     * @param data 追加节点的值
     */
    append (data) {
        let node = new ListNode(data);
        if (this.head === null) {
            this.head = node;
        } else {
            let current = this.head;
            while (current.next) {
                current = current.next;
            }
            current.next = node;
        }
        this.length += 1;
        return this;
    }
}

export default SinglyLinkedList;