Skip to content

Instantly share code, notes, and snippets.

@MichaelSitter
Last active January 16, 2018 23:10
Show Gist options
  • Save MichaelSitter/4f5fa0b414f4530ae60f01e869f95e88 to your computer and use it in GitHub Desktop.
Save MichaelSitter/4f5fa0b414f4530ae60f01e869f95e88 to your computer and use it in GitHub Desktop.
JS data structures - queue
'use strict';
function Node(item) {
this.value = item;
this.next = null;
}
function Queue() {
this.head = null;
this.tail = null;
}
Queue.prototype.queue = function (item) {
var node = new Node(item);
if (this.head === null) {
this.head = node;
this.tail = node;
} else {
this.tail.next = node;
this.tail = this.tail.next;
}
};
Queue.prototype.peek = function () {
if (this.items === null) {
throw new Error('element does not exist');
}
return this.items.value;
};
Queue.prototype.dequeue = function () {
if (this.head === null) {
throw new Error('element does not exist');
}
var val = this.head.value;
this.head = this.head.next;
return val;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment