函数功能:实现单链表的初始化,插入节点、删除节点、查找节点和删除节点功能;
/**
* 单链表构造函数
*/
function LinkedList () {
this.ptr = null;
this.head = null;
this.length = 0;
this.insert = insertNode;
this.delete = deleteNode;
this.search = searchNode;
this.traverse = traverseNode;
}
/**
* 定义链表节点
*/
function ListNode (data) {
this.data = data;
this.next = null;
}
/**
* 插入节点
*/
function insertNode (data) {
var node = new ListNode(data);
this.ptr = this.head;
if (!this.ptr) {
this.ptr = node;
this.head = node;
} else {
while (this.ptr) {
if (this.ptr.next) {
this.ptr = this.ptr.next;
} else {
break;
}
}
this.ptr.next = node;
}
this.length++;
}
/**
* 搜索节点
*/
function searchNode (data) {
this.ptr = this.head;
if (!this.ptr) {
return false;
}
while (this.ptr) {
if (this.ptr.data === data) {
return true;
} else if (this.ptr.next) {
this.ptr = this.ptr.next;
} else {
return false;
}
}
this.ptr = this.head;
}
function deleteNode (data) {
this.ptr = this.head;
if (!this.ptr) {
return false;
} else if (this.search(data)) {
this.ptr = this.head;
if (this.ptr.data === data) {
this.ptr = null;
this.head = null;
} else {
while (this.ptr.next) {
if (this.ptr.next.data === data) {
if (this.ptr.next.next) {
this.ptr.next = this.ptr.next.next;
} else {
this.ptr.next = null;
}
return true;
} else {
this.ptr = this.ptr.next;
}
}
}
this.length--;
} else {
return false;
}
}
/**
* 遍历输出
*/
function traverseNode () {
var p = this.head;
if (!this.head) {
return false;
}
while (this.head) {
console.log(this.head.data);
if (this.head.next) {
this.head = this.head.next;
} else {
break;
}
}
this.head = p;
}
/**
* 序列测试
*/
var list = new LinkedList();
list.insert('a');
console.log(list.length);
list.insert('b');
console.log(list.length);
list.insert('c');
console.log(list.length);
list.traverse();
console.log(list.search('b'));
list.delete('b');
list.insert('d');
list.traverse();
list.delete('a');
list.delete('c');
list.delete('d');
list.traverse();
list.insert('e');
list.traverse();
结果截图: