手写链表

653 阅读1分钟

今天来写一个链表

// 节点
class Node {
    constructor(element) {
        // 元素
        this.element = element

        // 指向下一元素的指针
        this.next = null
    }
}

// 链表
class NodeList {
    constructor() {
        // 头节点
        this.head = null

        // 记录长度
        this.length = 0
    }

    // 增加方法
    append(element) {
        let cur
        let node = new Node(element)
        if (this.head == null) {
            // 首次进来是空的,直接赋值head元素
            this.head = node
        } else {
            cur = this.head
            while (cur.next) {
                // 把当前的下一元素赋值到当前
                cur = cur.next
            }
            // 把node元素添加到末尾
            cur.next = node
        }
        // 记录长度加1
        this.length += 1
    }

    // 删除方法
    removeAt(index) {
        let length = this.length

        // 链表长度为0、参数大于链表长度减1、参数不是数字、参数小于0都属于非法参数
        if (!length || (index > length - 1) || !(typeof index === 'number') || index < 0) {
            throw new Error("非法参数");
        }
        let cur = this.head
        let prev
        let i = 0
        if (index == 0) {
            // 删除第一项,把下一节点指向head
            this.head = cur.next
        } else {
            while (i < index) {
                // 保存上一个和当前值
                prev = cur
                cur = cur.next
                i++
            }
            // 把要删除值的上一个值指向删除值的下一个值
            prev.next = cur.next

            // 把要删除值的下一节点置空
            cur.next = null
        }
        // 记录长度减1
        this.length -= 1

        // 返回删除值元素
        return cur.element
    }
}