Skip to content

Instantly share code, notes, and snippets.

@warrenday
Last active February 17, 2021 20:44
Show Gist options
  • Select an option

  • Save warrenday/169b751ccb96a34aa2f467bad71d9671 to your computer and use it in GitHub Desktop.

Select an option

Save warrenday/169b751ccb96a34aa2f467bad71d9671 to your computer and use it in GitHub Desktop.
Loop over a linked list
class LinkedList {
head = null
tail = null;
insert(data) {
const newNode = { data };
if (!this.head) {
this.head = newNode
} else {
this.tail.next = newNode;
}
this.tail = newNode;
}
*[Symbol.iterator]() {
let node = this.head;
while (node) {
yield node.data;
node = node.next;
}
}
}
const list = new LinkedList();
list.insert(10)
list.insert(20)
list.insert(30)
for (const item of list) {
console.log(item)
}
// Logs 10, 20, 30
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment