數據結構列表的JS實現

列表時一組有序的數據結構,每一個列表中的數據項稱爲元素。不包含任何元素的列表爲空列表,能夠在列表的末尾append一個元素,也能夠在列表中指定位置insert一個元素,關於列表的抽象數據類型的定義以下:數組

屬性或方法 描述
listSize(屬性) 列表的元素個數
pos(屬性) 列表中的當前位置
length(方法) 返回列表中元素的個數
clear(方法) 清空列表中的全部元素
toString(方法) 返回列表中字符串形式
getElement(方法) 返回當前位置的元素
insert(方法) 在列表指定位置後插入新元素
append(方法) 在列表末尾插入新元素
remove(方法) 刪除列表中的元素
contains(方法) 判斷列表中是否存在給定值
front(方法) 將列表中當前位置移動到第一個
end(方法) 將列表中當前位置移動到最後一個
prev(方法) 將當前位置前移一位
next(方法) 將當前位置後移一位
hasNext(方法) 判斷是否有後一位
hasPrev(方法) 判斷是否有前一位
currPos(方法) 返回列表的當前位置
moveTo(方法) 移動當前位置至指定位置

下面直接用代碼實現已列表類數據結構

// 爲了簡便,直接將方法放入對象中。最好時將方法放在prototype對象中。
function List() {
    this.listSize = 0;
    this.pos = 0;
    this.dataStore = [];
    this.clear = clear;
    this.toString = toString;
}

List.prototype.append = function(ele) {
    this.dataStore[this.listSize++] = ele;  //添加一個元素並將listSize加一
}

List.prototype.remove = function(ele) {
    var pos = this.find(ele);
    if(pos > -1) {
        this.dataStore.splice(pos,1);
        this.listSize--;
        return true;
    }
    return false;
}

List.prototype.find = function(ele) {
    for(var i = 0; i < this.dataStore.length; i++) {
        if(this.dataScore[i] === ele) {
            return i;
        }
    }
    return -1;
}

List.prototype.length = function() {
    return this.listSize;
}

List.prototype.toString = function() {
    return this.dataStore;
}

List.prototype.insert = function(ele,afterEle) {
    var insertPos = this.find(afterEle);
    if(insertPos !== -1) {
        this.dataStore.splice(insertPos+1,0,ele);
        this.listSize++;
        return true;
    }
    return false;
}

List.prototype.clear = function() {
    this.dataStore.length = 0;
    this.listSize = this.pos = 0;
}

List.prototype.contains = function(ele) {
    for(var i = 0; i < this.dataStore.length; i++) {
        if(this.dataScore[i] === ele) {
            return true;
        }
    }
    return false;
}

List.prototype.front = function() {
    this.pos = 0;
}

List.prototype.end = function() {
    this.pos = this.listSize - 1;
}

List.prototype.prev = function() {
    if(!this.pos) {
      this.pos--;  
    } 
}

List.prototype.next = function() {
    if(this.pos < this.listSize) {
      this.pos++;  
    } 
}

List.prototype.currPos = function() {
    return this.pos;
}

List.prototype.moveTo = function(pos) {
    return this.pos = pos;
}

List.prototype.getElement = function() {
    return this.dataStore[this.pos];
}

List.prototype.hasNext = function() {
    return this.pos<this.listSize;
}

List.prototype.hasPrev = function() {
    return this.pos>=0;
}

這樣列表的js現實就完成了。其中front(),end(),prev(),next()方法就實現了List類的一個迭代器。使用迭代器訪問和數組索引相比,有如下的一些優勢。app

  1. 訪問元素列表不用關係底層的數據存儲結構
  2. 向列表添加元素時,索引值會改變,而迭代器的訪問方式不會改變
  3. 爲訪問列表裏的元素提供了統一的方式
// 使用迭代器訪問
var test = new List()
test.append("Jack");
test.append("Rose")
for(test.front(); test.hasNext(); test.next()) {
    console.log(test.getElement())   // Jack   //Rose
}
相關文章
相關標籤/搜索