JS中數據結構之列表
列表是一組有序的數據。每個列表中的數據項稱為元素。在 JavaScript 中,列表中的元素可以是任意數據類型。列表中可以保存多少元素并沒有事先限定并可以不斷壯大,實際使用時元素的數量受到程序內存的限制。
(1)列表的抽象數據類型定義:
listSize(屬性) 列表的元素個數
pos(屬性) 列表的當前位置
length(屬性) 返回列表中元素的個數
clear(方法) 清空列表中的所有元素
toString(方法) 返回列表的字符串形式
getElement(方法) 返回當前位置的元素
insert(方法) 在現有元素后插入新元素
append(方法) 在列表的末尾添加新元素
remove(方法) 從列表中刪除元素
front(方法) 將列表的當前位置設移動到第一個元素
end(方法) 將列表的當前位置移動到最后一個元素
prev(方法) 將當前位置后移一位
next(方法) 將當前位置前移一位
currPos(方法) 返回列表的當前位置
moveTo(方法) 將當前位置移動到指定位置
(2)實現列表類
function List() { this.listSize = 0; this.pos = 0; this.dataStore = []; // 初始化一個空數組來保存列表元素 this.clear = clear; this.find = find; this.toString = toString; this.insert = insert; this.append = append; this.remove = remove; this.front = front; this.end = end; this.prev = prev; this.next = next; this.length = length; this.currPos = currPos; this.moveTo = moveTo; this.getElement = getElement; this.length = length; this.contains = contains; }
append()方法給列表的下一個位置增加一個新的元素,這 個位置剛好等于變量 listSize 的值
function append(element) { this.dataStore[this.listSize++] = element; }
find()方法在列表中查找某一元素,如果找到,就返回該 元素在列表中的位置,否則返回 -1
function find(element) { for (var i = 0; i < this.dataStore.length; ++i) { if (this.dataStore[i] == element) { return i; } } return -1; }
remove()方法從列表中刪除元素。首先,需要在列表中找到該元素,然后刪除它
function remove(element) { var foundAt = this.find(element); if (foundAt > -1) { this.dataStore.splice(foundAt,1); --this.listSize; return true; } return false; }
length()方法返回列表中有多少個元素
function length() { return this.listSize; }
toString():顯示列表中的元素
function toString() { return this.dataStore; }
insert():向列表中插入一個元素,這里的插入是指插入到指定的列表中的元素之后
function insert(element, after) { //element:要插入的元素,after:列表中指定的元素(element插入到該元素之后) var insertPos = this.find(after); //find() 方法尋找傳入的 after 參數在列表中的位置 if (insertPos > -1) { this.dataStore.splice(insertPos+1, 0, element); ++this.listSize; return true; } return false; }
clear():清空列表中所有的元素。clear() 方法使用 delete 操作符刪除數組 dataStore,接著在下一行創建一個空數組。最后一行將 listSize 和 pos 的值設為 1,表明這是一個新的空列表。
function clear() { delete this.dataStore; this.dataStore = []; this.listSize = this.pos = 0; }
contains():判斷給定值是否在列表中
function contains(element) { for (var i = 0; i < this.dataStore.length; ++i) { if (this.dataStore[i] == element) { return true; } } return false; }
遍歷列表
function front() { this.pos = 0; } function end() { this.pos = this.listSize-1; } function prev() { if (this.pos > 0) { --this.pos; } } function next() { if (this.pos < this.listSize-1) { ++this.pos; } } function currPos() { return this.pos; } function moveTo(position) { this.pos = position; } function getElement() { return this.dataStore[this.pos]; }
使用迭代器遍歷列表。使用迭代器,可以不必關心數據的內部存儲方式,以實現對列表的遍歷
for(names.front(); names.currPos() < names.length();names.next()) { print(names.getElement()); }
列表數據結構可解決問題舉例:影碟租賃程序:使用列表管理影碟,將數據讀入列表,當有人借影碟時將元素移出。

浙公網安備 33010602011771號