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

你可能感兴趣的:(JS简单实现一个链表)