function LinkList() {
function LinkNode(data) {
this.data = data;
this.next = null;
}
this.length = 0;
this.head = new LinkNode();
function isEmpty() {
return this.length === 0;
}
function clear() {
this.traverse(function(elem, index) {
delete elem;
});
this.head.next = null;
this.length = 0;
}
function get(index) {
if (index < 0) {
index = this.length + index - 1;
}
if (index < 0 || index >= this.length) {
return null;
}
var nowElem = this.head.next;
var i = 0;
while (i < index) {
nowElem = nowElem.next;
i++;
}
return nowElem.data;
}
function set(data, index) {
if (index < 0) {
index = this.length + index - 1;
}
if (index < 0 || index >= this.length) {
return false;
}
var nowElem = this.head.next;
var i = 0;
while (i < index) {
nowElem = nowElem.next;
i++;
}
nowElem.data = data;
return true;
}
function traverse(callback) {
if (Object.prototype.toString.call(callback) !== "[object Function]") {
throw new TypeError("callback is not a function");
}
if (!this.isEmpty()) {
var nowElem = this.head,
nextElem = nowElem.next;
var index = 0;
while (nextElem) {
nowElem = nextElem;
nextElem = nextElem.next;
callback(nowElem, index++, this);
}
}
}
function indexOf(data) {
var index = -1;
if (this.length > 0) {
var nowElem = this.head.next;
var i = 0;
while (i < this.length && nowElem.data !== data) {
nowElem = nowElem.next;
i++;
}
if (i < this.length) {
index = i;
}
}
return index;
}
function insert(data, index) {
index = index || 0;
if (this.length > 0) {
var i = 0;
var nowElem = this.head;
if (index < 0) {
index = this.length + index;
if (index < 0) {
index = 0;
}
}
while (i < this.length && i < index) {
nowElem = nowElem.next;
i++;
}
var nextElem = nowElem.next;
nowElem.next = new LinkNode(data);
nowElem.next.next = nextElem;
} else {
this.head.next = new LinkNode(data);
}
this.length++;
}
function append(data) {
var nowElem = this.head;
for (var i = 0; i < this.length; i++) {
nowElem = nowElem.next;
}
nowElem.next = new LinkNode(data);
this.length++;
}
function remove(index) {
if (index < 0) {
index = this.length + index - 1;
}
if (index > 0 && index < this.length) {
var nowElem = this.head;
for (var i = 0; i < this.length; i++) {
if (i === index) {
var deleteElem = nowElem.next;
nowElem.next = deleteElem.next;
delete deleteElem;
this.length--;
return true;
}
nowElem = nowElem.next;
}
}
return false;
}
this.clear = clear;
this.get = get;
this.set = set;
this.traverse = traverse;
this.indexOf = indexOf;
this.append = append;
this.insert = insert;
this.remove = remove;
this.isEmpty = isEmpty;
}
JavaScript实现单项链表
猜你喜欢
转载自blog.csdn.net/xukun5137/article/details/78194832
今日推荐
周排行