这节我们实现一个单链表,有详细的注释。之前贴出代码好了
/*
链表数据结构的实现
*/
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);