# 基于链表实现的迭代器

``````class Node {
constructor(value) {
this.value = value;
this.next = null;
}
}``````

``````class LinkList {
constructor() {
this.count = 0;
}

push(val) {
const node = new Node(val);
} else {
while (current.next != null) {
current = current.next;
}
current.next = node;
}

this.count++;
return this.count;
}

removeAt(index) {
if (index >= 0 && index < this.count) {
if (index === 0) {
} else {
// 上一个
let prev = this.getElementAt(index - 1);
let current = prev.next;
prev.next = current.next;
}
this.count--;
}

return undefined;
}
getElementAt(index) {
if (index >= 0 && index < this.count) {
let current;
if (index === 0) {
} else {
for (let i = 0; i < index; i++) {
current = current.next;
}
}
return current;
}
return undefined;
}
insert(element, index) {
if (index >= 0 && index < this.count) {
let node = new Node(element)
if (index === 0) {
} else {
// 上一个
let prev = this.getElementAt(index - 1);
let next = prev.next;
node.next = next;
prev.next = node;
}
this.count++;
return element;
}

return undefined;
}
indexOf(element) {
for (let i = 0; i < this.count; i++) {
if (current.value === element) {
return i;
}
current = current.next;
}

return undefined;
}
}
remove(element) {
const index = this.indexOf(element);
this.removeAt(index);
}
isEmpty() {
return this.size() === 0;
}
size() {
return this.count;
}
toString() {
let str = `\${current.value}`;
for (let i = 1; i < this.count; i++) {
current = current.next;
str = `\${str},\${current.value}`;
}
return str;
}
}``````

``````LinkList.prototype.entries = function() {
const count = this.count;
let selfCount = 0;
return new function() {
this.next = function() {
if(selfCount > count || current == null) {
return {value: undefined, done: true};
}
let [index, value] = [selfCount, current.value];
selfCount++;
let done = count === selfCount;

current = current.next;
return {index, value, done};
}
}
}``````

``````let l = new LinkList();
l.push(1);
l.push(2);
l.push(3);
l.insert(1.5, 1)
const item = l.entries();
console.log(item.next())
console.log(item.next())
console.log(item.next())
console.log(item.next())
console.log(item.next())
console.log(item.next())
console.log(item.next())
console.log(item.next())``````