js實現個鏈表吧

存儲多個元素,最經常使用的數據結構是數組。可是數組有個一缺點,從數組中添加或移除項的成本很高,由於須要移動元素。鏈表也能夠存儲有序的元素集合,可是和數組不一樣,鏈表中的元素在內存中不是連續放置的。每一個元素存儲自己節點值和下一個元素的引用,鏈表的一個好處在於,添加或移除元素的時候不須要移動其餘元素。
ok,開始實現咱們的數據結構,骨架以下node

function LinkedList() {
    var Node = function (val) {
        this.val = val;
        this.next = null;
    }; //Node輔助類
    var length = 0;
    var head = null;
    this.append = function (ele) {}; //追加
    this.insert = function (pos, ele) {}; //插入
    this.removeAt = function (pos) {}; //移除
    this.indexOf = function (ele) {}; //查找元素
    this.isEmpty = function () {}; //是否爲空
    this.size = function () {}; //鏈表元素個數
    this.getHead = function () {}; //鏈表頭
    this.toString = function () {}; //轉換爲字符串
}

首先實現向鏈表尾部追加元素吧:數組

this.append = function (ele) {
    var node = new Node(ele),
        current;
    if (head == null) {
        head = node;
    } else {
        current = head;
        //找到最後一項
        while (current.next) {
            current = current.next;
        }
        //將最後一項的next指向 node
        current.next = node;
    }
    length++; //更新鏈表長度
}

繼續實現鏈表插入數據結構

this.insert = function (pos, ele) {
    var node = new Node(ele);
    var idx = 0,
        previous,
        current = head;
    // 檢查是否越界
    if (pos >= 0 && pos <= length) {
        if (pos === 0) {
            node.next = current;
            head = node;
        } else {
            while (idx < pos) {
                previous = current; //保存前一個節點的引用
                current = current.next;
                idx++;
            }
            node.next = current; //節點的next指向current
            previous.next = node; //前一個節點指向node
            length++; //更新數組長度
        }
    } else {
        return false;
    }
}

鏈表的移除:app

this.removeAt = function (pos) {
    var current = head;
    var idx = 0,
        previous;
    //檢查越界
    if (pos >= 0 && pos <= length) {
        if (pos === 0) {
            head = current.next;
        } else {
            while (idx < pos) {
                previous = current;
                current = current.next;
                idx++;
            }
            previous.next = current.next; //前一個節點指向下一個節點
        }
        length--; //更新鏈表長度
        return current.val;
    } else {
        return null
    }
}

其餘方法就比較簡單了,實現以下:this

this.isEmpty = function () {
    return !length;
}
this.size = function () {
    return length;
}
this.getHead = function () {
    return head;
}
this.toString = function () {
    var str = '';
    var current = head;
    while (current) {
        str = str + ',' + current.val;
        current = current.next;
    }
    return str.slice(1);
}
相關文章
相關標籤/搜索