美文网首页
JS简单实现一个链表

JS简单实现一个链表

作者: ashyanSpada | 来源:发表于2021-05-04 20:37 被阅读0次

    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;
            }
        }
    }
    

    相关文章

      网友评论

          本文标题:JS简单实现一个链表

          本文链接:https://www.haomeiwen.com/subject/krlhdltx.html