鏈式結構 node
建立LinkedList,而且鏈表包含如下方法。數組
function LinkedList() {
let length = 0, // 鏈表的長度
head = null; // 鏈表的頭指針
// 輔助類
let Node = function(element) {
this.element = element;
this.next = null;
}
// 向鏈表尾部添加指定元素
this.append = function(element) {
let node = new Node(element),
current = '';
if (head === null) {
// 鏈表爲空
head = node;
} else {
// 鏈表不爲空,迭代到鏈表最後一項,最後一項的指針等於node
current = head;
while (current.next) {
current = current.next;
}
current.next = node;
}
length++;
};
// 從鏈表移除指定位置的元素
this.removeAt = function(position) {
// 檢查是否越界
if (position > -1 && position < length) {
let current = head,
previous = '',
index = 0;
if (position === 0) {
head = current.next;
} else {
while (index++ < position) {
previous = current;
current = current.next;
}
// 將previous與current的下一項連接起來,跳過current,從而移除它
previous.next = current.next;
}
length--;
return current.element;
} else {
return null;
}
};
// 在任意位置插入元素
this.insert = function(position, element) {
// 檢查是否越界
if (position > -1 && position < length) {
let node = new Node(element),
current = head,
previous = '',
index = 0;
if (position === 0) {
// 在第一個位置添加
head = node;
node.next = current;
} else {
while (index++ < position) {
previous = current;
current = current.next;
}
previous.next = node;
node.next = current;
}
length++;
return true;
} else {
return false;
}
};
// 返回指定項的索引
this.indexOf = function(element) {
let current = head,
index = 0;
while (current) {
if (element === current.element) {
return index;
} else {
index++;
current = current.next;
}
}
};
// 刪除指定元素
this.remove = function(element) {
let index = this.indexOf(element);
return this.removeAt(index, element);
};
// 鏈表是否爲空
this.isEmpty = function() {
return length === 0;
};
// 鏈表長度
this.size = function() {
return length;
};
// 把鏈表轉換爲一個字符串
this.toString = function() {
let current = head,
string = '';
while(current) {
string += current.element + (current.next ? 'n' : '');
current = current.next;
}
return string;
};
}
複製代碼
// 向鏈表添加一項bash
// 鏈表刪除一項鏈表相對傳統數組優勢是:添加刪除元素不會移動其它元素。數據結構
鏈表相對傳統數組缺點是:訪問鏈表中間的元素,須要從頭迭代,直到找到所需元素。app
下一篇文章:雙向鏈表、循環鏈表ui