2019年3月13日 星期三

DoublyLinkedList

module.exports = DoublyLinkedList;


// 雙向連結
function DoublyLinkedList() {

    let head;
    let tail;
    let length;

    this._head = function (node) {
        if (node == null) {
            return head;
        } else {
            head = node;
        }
    };

    this._tail = function (node) {
        if (node == null) {
            return tail;
        } else {
            tail = node;
        }
    };

    this._length = function (_length) {
        if (_length == null) {
            return length;
        } else {
            length = _length;
        }
    };

}

(function () {
    this.append = function (el) {
        debugger;

        let node = new Node(el);

        if (this._head() == null) {
            this._head(node);

            this._length(1);
            this._tail(node);

        } else {
            let prev_node = this._head();
            let count = 0;

            while (prev_node.next != null) {
                prev_node = prev_node.next;
                count++;
            }

            prev_node.next = node;
            node.prev = prev_node;

            this._length(++count);
            this._tail(prev_node);
        }

    };

    this.insert = function (position, el) {

    };

    this.remove = function (el) {

    };

    this.removeAt = function (position) {

    };

    this.indexOf = function (position) {

    };

    this.size = function () {
        return this._length();
    };

    this.toJSON = function () {
        debugger;
        let res = [];
        let node = this._head();

        do {
            if (node == null) {
                break;
            } else {
                res.push(JSON.stringify(node.element));
            }
        } while ((node = node.next) != null);

        return res.join(',');
    };

}).call(DoublyLinkedList.prototype);


//==============================================================================

function Node(el) {
    this.element = el;
    this.prev = null;
    this.next = null;
}