Created
February 9, 2021 04:31
-
-
Save bishil06/a80d839a2e5f04e15b83b993d59be86a to your computer and use it in GitHub Desktop.
_JavaScript_queue
This file contains hidden or 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 Queue { | |
constructor() { | |
this.list = []; | |
this.first = null; | |
} | |
enqueue(v) { | |
if (this.first === null) { | |
this.first = v; | |
} | |
this.list.push(v); | |
} | |
depueue() { | |
if (this.first === null) { | |
return null; | |
} | |
let [remove, ...rest] = this.list; | |
this.list = rest; | |
if (this.list.length === 0) { | |
this.first = null; | |
} | |
else { | |
this.first = this.list[0]; | |
} | |
return remove; | |
} | |
peek() { | |
return this.first; | |
} | |
} | |
const q = new Queue(); | |
q.enqueue(1) | |
q.enqueue(2) | |
q.enqueue(3) | |
console.log(q.peek()); // 1 | |
console.log(q.depueue()); // 1 | |
console.log(q.peek()); // 2 | |
console.log(q.depueue()); // 2 | |
console.log(q.peek()); // 3 | |
console.log(q.depueue()); // 3 | |
console.log(q.peek()); // null |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment