Last active
November 4, 2020 14:15
-
-
Save cevaris/a863c4af22f1d1121acd2026ea6cff0b to your computer and use it in GitHub Desktop.
LinkList iterator method
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export class LinkedList { | |
constructor() { | |
this.head = null; | |
} | |
*iterator() { | |
let temp = this.head; | |
while (temp && temp.next) { | |
yield temp.value; | |
temp = temp.next; | |
} | |
// capture the last node if non-null | |
if (temp) { | |
yield temp.value; | |
} | |
} | |
/** | |
* Defines an iterator such that callers can easily iterate over LinkedList. | |
* ex. | |
* | |
* for (const e of list) { | |
* console.log(e); | |
* } | |
*/ | |
[Symbol.iterator]() { | |
return this.iterator(); | |
} | |
} | |
class Node { | |
constructor(value, next = null) { | |
this.value = value; | |
this.next = next; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment