// 封装链表类
class LinkedList {
constructor() {
// 内部的类:节点类
function Node(data) {
this.data = data;
this.next = null;
}
// 属性
this.head = null;
this.length = 0;
// 方法
let current, previous, index;
// 1.append方法
LinkedList.prototype.append = data => {
const newNode = new Node(data);
if (this.length === 0) {
this.head = newNode;
} else {
current = this.head;
while (current.next) {
current = current.next;
}
current.next = newNode;
}
this.length += 1;
};
// 2.toString方法
LinkedList.prototype.toString = () => {
current = this.head;
let listString = '';
while (current) {
listString += current.data + ' ';
current = current.next;
}
return listString;
};
// 3.insert方法
LinkedList.prototype.insert = (position, data) => {
if (position < 0 || position > this.length) return false;
const newNode = new Node(data);
index = 0;
current = this.head;
previous = null;
if (position === 0) {
newNode.next = this.head;
this.head = newNode;
} else {
while (index++ < position) {
previous = current;
current = current.next;
}
newNode.next = current;
previous.next = newNode;
}
this.length += 1;
return true;
};
// 4.get方法
LinkedList.prototype.get = position => {
if (position < 0 || position >= this.length) return null;
current = this.head;
index = 0;
while (index++ < position) {
current = current.next;
}
return current.data;
};
// 5.indexOf方法
LinkedList.prototype.indexOf = data => {
current = this.head;
index = 0;
while (current) {
if (current.data === data) {
return index;
} else {
current = current.next;
index += 1;
}
}
return -1;
};
// 6.update方法
LinkedList.prototype.update = (position, newData) => {
if (position < 0 || position >= this.length) return false;
index = 0;
current = this.head;
while (index++ < position) {
current = current.next;
}
current.data = newData;
return true;
};
// 7.removeAt方法
LinkedList.prototype.removeAt = position => {
if (position < 0 || position > this.length) return null;
current = this.head;
index = 0;
previous = null;
if (position === 0) {
this.head = this.head.next;
} else {
while (index++ < position) {
previous = current;
current = current.next;
}
previous.next = current.next;
}
this.length -= 1;
return current.data;
};
// 8.remove方法
LinkedList.prototype.remove = data => {
const position = this.indexOf(data);
return this.removeAt(position);
};
// 9.isEmpty方法
LinkedList.prototype.isEmpty = () => this.length === 0;
// 10.size方法
LinkedList.prototype.size = () => this.length;
}
}
js封装单向链表
最新推荐文章于 2024-08-19 10:59:54 发布