function LinkArray() {
// 实例属性
this.head = null; // 链表的头节点
this.length = 0; // 记录链表的长度
// 内部函数
function Node(data) {
this.data = data;
this.next = null;
}
// 定义原型方法
LinkArray.prototype.append = function (data) {
// 创建新结点
var newNode = new Node(data);
// 判断指针是否为NULL
if (this.head == null) {
this.head = newNode;
}
else {
// 定义当前结点
var current = this.head;
// 循环找当前结点
while (current.next) {
current = current.next;
}
// 找到当前结点后,将其next指向newNode
current.next = newNode;
}
this.length++;
}
LinkArray.prototype.toString = function () {
var current = this.head;
var string = "";
while (current) {
string += current.data;
current = current.next;
}
return string;
}
LinkArray.prototype.insert = function (position, data) {
// 创建元素
var newNode = new Node(data);
// 元素为空的情况
if (this.head == null) {
this.head = newNode;
this.length++;
return true;
}
// 边界判断
if (position < 0 || position >= this.length) return false;
/* 插入分为三种情况*/
// 头插入
if (position == 0) {
var current = this.head;
newNode.next = current;
this.head = newNode;
}
// 尾插入
else if (position == this.length - 1) {
var current = this.head;
while (current.next) {
current = current.next;
}
current.next = newNode;
}
// 中间插入 找到要插入结点的前一个结点
else {
var current = this.head;
var index = 0;
while (index++ != position - 1) {
current = current.next;
}
var temp = current.next;
current.next = newNode;
newNode.next = temp;
}
this.length++;
return true;
}
LinkArray.prototype.get = function (position) {
// 判断边界
if (position < 0 || position >= this.length) return null;
var current = this.head;
while (position--) {
current = current.next;
}
return current.data;
}
LinkArray.prototype.indexOf = function (data) {
var current = this.head;
var index = 0;
while (current) {
if (current.data == data) {
return index;
}
current = current.next;
index++;
}
return -1;
}
LinkArray.prototype.update = function (position, data) {
if (position < 0 || position >= this.length) return false;
var current = this.head;
while (position--) {
current = current.next;
}
current.data = data;
return true;
}
LinkArray.prototype.removeAt = function (position) {
if (position < 0 || position >= this.length) return false;
var current = this.head;
/* 删除分为3三种情况*/
// 头删除
if (position == 0) {
this.head = current.next;
}
// 尾删除
else if (position == this.length - 1) {
while ((position--) > 1) {
current = current.next;
}
current.next = null;
}
// 中间删除 思想:找到要删除元素的前一个,直接跨过当前元素 连接当前元素的下一个元素。
else {
var index = 0;
while (index++ != position - 1) {
current = current.next;
}
var temp = current.next;
current.next = temp.next;
}
this.length--;
return true;
}
LinkArray.prototype.remove = function (data) {
var position = this.indexOf(data);
return this.removeAt(position);
}
LinkArray.prototype.isEmpty = function () {
return this.length == 0 ? true : false;
}
LinkArray.prototype.size = function () {
return this.length;
}
}
var l = new LinkArray();
l.insert(0, "123 ")
l.insert(0, "124 ")
console.log(l.toString());