之前我们用2种方法实现了单链表,现在我们将再增加一种方法。
function LinkedList() {
var Node = function (value) {
this.value = value;
this.next = null;
}
var head = null;
var length = 0;
/* 1)使用一个辅助函数来实现递归*/
this.append1 = function (value) {
var new_node = new Node(value);
if(head == null) {
head = new_node;
} else {
appendNode(head, new_node);
}
length++;
function appendNode(parent, new_node) {
if(parent.next == null) {
parent.next = new_node;
} else {
insertNode(parent.next, new_node);
}
}
}
/* 2)不使用辅助函数来实现递归 */
this.append2 = function (value, parent, new_node) {
/*
使用parent保存中间节点
*/
var new_node = new_node || (new Node(value));
if(head == null) {
head = new_node;
length++;
} else {
var current = parent || head;
if(current.next == null) {
current.next = new_node;
length++;
} else {
this.append2(value, current.next, new_node);
}
}
}
/* 3) 不使用递归*/
this.append3 = function (value) {
var new_node = new Node(value);
if(head == null) {
head = new_node;
} else {
var current = head;
while(current.next != null) {
current = current.next;
}
current.next = new_node;
}
length++;
}
this.getHead = function () {
return head;
}
/*一个遍历函数*/
this.traverse = function () {
var current = head;
while(current != null) {
console.log(current.value);
current = current.next;
}
}
this.size = function () {
return length;
}
}
var arr = [8, 7, 4, 3, 2, 9, 20];
var linked_list = new LinkedList();
for(var i=0; i<arr.length; ++i) {
linked_list.append2(arr[i]);
}
var head = linked_list.getHead();