class LinkedList {
constructor() {
this.head = null;
}
}
class LinkedNode {
constructor(data, next = null) {
(this.data = data), (this.next = next);
}
}
LinkedList.prototype.length = function () {
let node = this.head;
let length = 0;
while (node) {
length++;
node = node.next
}
return length;
}
LinkedList.prototype.get = function (index) {
if (index < 0 || index > this.length()) {
throw new RangeError('下标参数越界');
}
let node = this.head;
let count = 0;
while (node) {
if (count === index) {
return node;
}
count++;
node = node.next;
}
return null;
}
LinkedList.prototype.insert = function (data, index = 0) {
if (index < 0 || index > this.length()) {
throw new RangeError('下标参数越界');
}
let newNode = new LinkedNode(data);
if (index == 0) {
newNode.next = this.head;
this.head = newNode;
return this.head;
}
let preNode = this.get(index - 1);
newNode.next = preNode.next;
preNode.next = newNode;
return this.head;
}
LinkedList.prototype.delete = function (index) {
if (index < 0 || index > this.length()) {
throw new RangeError('下标参数越界');
}
if (index == 0) {
let temp;
temp = this.head;
this.head = this.head.next;
return temp;
}
let cur = this.get(index);
let preNode = this.get(index - 1);
preNode.next = cur.next;
cur.next = null;
return cur;
}
LinkedList.prototype.update = function (newData, index) {
if (index < 0 || index > this.length()) {
throw new RangeError('下标参数越界');
}
this.get(index).data = newData;
}
LinkedList.prototype.reserve = function () {
let p = this.head;
let q = p.next;
let r = q.next;
p.next = null;
while (q.next) {
q.next = p;
p = q;
q = r;
r = r.next;
}
q.next = p;
this.head = q;
}
LinkedList.prototype.forEach = function (fn) {
let node = this.head;
while (node) {
fn.call(this, node);
node = node.next;
}
}
B
LinkedList.prototype.toArray = function () {
let array = [];
this.forEach((node) => { array.push(node) });
return array;
}