JS簡(jiǎn)單實(shí)現(xiàn)一個(gè)鏈表

JS簡(jiǎn)單實(shí)現(xiàn)一個(gè)鏈表

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;
        }
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 一、節(jié)點(diǎn)的實(shí)現(xiàn) 我都知道鏈表就是用有向線段把多個(gè)節(jié)點(diǎn)按順序串起來,要實(shí)現(xiàn)鏈表首先要實(shí)現(xiàn)節(jié)點(diǎn),而每一個(gè)節(jié)點(diǎn),有一個(gè)自...
    Canace22閱讀 437評(píng)論 0 1
  • 整個(gè)單向鏈表引用類型的程序如下: 實(shí)現(xiàn)單向鏈表要注意的地方是,js沒有指針,因此可以在最開始創(chuàng)建一個(gè)哨兵節(jié)點(diǎn),它的...
    星月西閱讀 1,991評(píng)論 0 2
  • ??要存儲(chǔ)多個(gè)元素,數(shù)組(或列表)可能是最常用的數(shù)據(jù)結(jié)構(gòu)。但這種數(shù)據(jù)結(jié)構(gòu)有一個(gè)缺點(diǎn):(在大多數(shù)語(yǔ)言中)數(shù)據(jù)的大小是...
    小小的開發(fā)人員閱讀 2,312評(píng)論 0 5
  • 文章首發(fā)于 www.shaotianyu.com 一、數(shù)組和鏈表優(yōu)缺點(diǎn) 1.1、數(shù)組(Array) 1.1.1 數(shù)...
    ShaoSoy閱讀 361評(píng)論 0 0
  • 自己總結(jié)了一下鏈表的基本操作的實(shí)現(xiàn),文末還有幾道簡(jiǎn)單的算法題可供練習(xí)! 前端校招準(zhǔn)備系列--使用js實(shí)現(xiàn)鏈表的操作...
    huhaha24閱讀 734評(píng)論 0 1

友情鏈接更多精彩內(nèi)容