class ListNode {
constructor(data = null, next = null) {
this.data = data;
this.next = next;
}
}
const list = [1, 22, '1', 444, 55555];
const fnListNode = (i = 0, n = list.length) => i < n ? new ListNode(list[i], fnListNode(i + 1, n)) : null;
list.head = fnListNode();
// demo
Object.assign(Object.prototype, {
removeAt(postion) {
// var curent; var 会提升的 赋值并不会
if (postion < 0 || postion >= this.length) return null;
if (postion == 0) {
this.head = this.head.next;
} else {
var current = this.head;
var previous = null;
var index = 0;
while (index++ < postion) {
previous = current;
current = current.next;
}
previous.next = current.next;
}
this.length--;
return current.data;
// return current?.data;
},
remove(data) {
var value = this.indexOf(data);
return this.removeAt(value);
}
});
// test
console.log(list.removeAt(4));
console.log(list);
list.remove('1');
console.log(list.head);
list.remove(1); // 你找到0才报错吧 比如找1然后indeOf返回下标0 然后进if 不走else了 current就是undefined 跟5楼大佬说的差不多吧