Last active
November 14, 2021 15:38
-
-
Save kleinron/9d9fe8dece1f038f376db4206438b9c5 to your computer and use it in GitHub Desktop.
minimal implementation for a queue backed by a singly linked list
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
class LinkedQueue { | |
constructor() { | |
this._newest = null; | |
this._oldest = null; | |
this._size = 0; | |
} | |
enqueue(item) { | |
if (this._size === 0) { | |
this._newest = {value: item, next: null}; | |
this._oldest = this._newest; | |
} else { | |
const temp = {value: item, next: null}; | |
this._newest.next = temp; | |
this._newest = temp; | |
} | |
this._size++; | |
} | |
dequeue() { | |
const oldest = this._oldest; | |
const result = oldest.value; | |
oldest.value = null; | |
this._oldest = oldest.next; | |
this._size--; | |
return result; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment