這節我們實現一個單鏈表,有詳細的註釋。之前貼出代碼好了
/*
鏈表數據結構的實現
*/
function LinkedList() {
var Node = function (element) {
this.element = element;
this.next = null;
}
var length = 0;
var head = null;
/*向列表尾部追加節點*/
this.append = function (element) {
var new_node = new Node(element);
if(head == null) {
head = new_node;
} else {
//insertNode(head, new_node); // 使用遞歸來解決也可以
var current = head;
while(current.next != null) {
current = current.next;
}
current.next = new_node;
}
length++;
}
// /*這裏*/
// function insertNode(root, new_node) {
// if(root.next == null) {
// root.next = new_node;
// } else {
// insertNode(root.next, new_node);
// }
// }
/*向列表特定位置插入節點*/
this.insert = function (position, element) {
if(position < 0 || position>this.size()-1) {
throw new Error("Position should be in [0, " + (this.size() -1) + "]");
}
var new_node = new Node(element);
if(position == 0) {
new_node.next = head;
head = new_node;
} else {
var current = head;
for(var i=1; i<position; ++i) {
current = current.next;
}
new_node.next = current.next;
current.next = new_node;
}
length++;
}
/*移除特定位置的節點*/
this.removeAt = function (position) {
if(position < 0 || position>this.size()-1) {
throw new Error("Position should be in [0, " + (this.size() -1) + "]");
}
if(position == 0) {
head = head.next;
} else {
var current = head;
for(var i=1; i<position; ++i) {
current = current.next;
}
current.next = current.next.next;
}
length--;
}
/*按值相等移除遇到的第一個節點*/
this.remove = function (element) {
var index = this.indexOf(element);
if(index == -1) {
return;
}
this.removeAt(index);
}
/*按值相等返回遇到的第一個節點的位置*/
this.indexOf = function (element) {
var current = head;
var cnt = -1;
while(current != null) {
cnt++;
if(element == current.element) {
return cnt;
}
current = current.next;
}
if(current == null) {
return -1;
}
}
/*判斷鏈表是否爲空*/
this.isEmpty = function () {
return length == 0;
}
/*返回鏈表的大小*/
this.size = function () {
return length;
}
/*返回鏈表的頭指針或者稱爲引用*/
this.getHead = function () {
return head;
}
/*鏈表只輸出值*/
this.toString = function () {
var current = head;
var arr = [];
while(current != null) {
arr.push(current.element);
current = current.next;
}
return arr.join(",");
}
/*按順序打印鏈表*/
this.print = function () {
console.log(this.toString());
}
}
/* Here is a test function */
function test(arr) {
var linked_list = new LinkedList();
for(var i=0; i<arr.length; ++i) {
linked_list.append(arr[i])
}
return linked_list;
}
var arr = [10, 20, 30, 40, 50];
var result = test(arr);