JS简单实现一个链表

JS简单实现一个链表

class Node {
    constructor (val, front, back) {
        this.val = val;
        this.front = front;
        this.back = back;
    }
}

class List {
    constructor () {
        this.head = null;
        this.tail = null;
        this.length = 0;
    }
    addToBack (el) {
        if (this.tail) {
            this.tail.back = el;
            el.front = this.tail;
            this.tail = el;
        } else {
            this.head = el;
            this.back = el;
            this.length += 1;
        }
    }
    addToFront (el) {
        if (this.head) {
            el.back = this.head;
            this.head.front = el;
            this.head = el;
        } else {
            this.head = el;
            this.back = el;
            this.length += 1;
        }
    }
    moveToFront (el) {
        if (this.head === el) {
            return
        } else {
            this.remove(el);
            this.addToFront(el);
        }
    }
    moveToBack (el) {
        if (this.tail === el) {
            return
        } else {
            this.remove(el);
            this.addToBack(el);
        }
    }
    remove (el) {
        if (this.head === el && this.tail === el) {
            this.head = null;
            this.tail = null;
        } else if (this.head === el) {
            this.head = el.back;
            el.back.front = null;
            el.back = null;
        } else if (this.back === el) {
            this.tail = el.front;
            el.front.back = null;
            el.front = null;
        } else {
            const front = el.front;
            const back = el.back;
            front.back = back;
            back.front = front;
            el.front = null;
            el.back = null;
        }
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 一、节点的实现 我都知道链表就是用有向线段把多个节点按顺序串起来,要实现链表首先要实现节点,而每一个节点,有一个自...
    Canace22阅读 3,038评论 0 1
  • 整个单向链表引用类型的程序如下: 实现单向链表要注意的地方是,js没有指针,因此可以在最开始创建一个哨兵节点,它的...
    星月西阅读 5,915评论 0 2
  •   要存储多个元素,数组(或列表)可能是最常用的数据结构。但这种数据结构有一个缺点:(在大多数语言中)数据的大小是...
    小小的开发人员阅读 6,666评论 0 5
  • 文章首发于 www.shaotianyu.com 一、数组和链表优缺点 1.1、数组(Array) 1.1.1 数...
    ShaoSoy阅读 2,498评论 0 0
  • 自己总结了一下链表的基本操作的实现,文末还有几道简单的算法题可供练习! 前端校招准备系列--使用js实现链表的操作...
    huhaha24阅读 3,911评论 0 1