Skip to content

Instantly share code, notes, and snippets.

@tpae
Last active August 13, 2021 07:04
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tpae/42488a621a25847ebe75f59d469a0912 to your computer and use it in GitHub Desktop.
Save tpae/42488a621a25847ebe75f59d469a0912 to your computer and use it in GitHub Desktop.
JavaScript implementation of Queue Data Structure
// Implement a Queue using LinkedLists
// we know that queue is LIFO
// operations: enqueue, dequeue
function QueueNode(val) {
this.val = val;
this.next = null;
}
function Queue() {
this.head = null;
this.tail = null;
}
Queue.prototype.enqueue = function(val) {
var node = new QueueNode(val);
if (this.head == null && this.tail == null) {
this.head = node;
this.tail = node;
} else {
if (this.tail !== null) {
this.tail.next = node;
this.tail = node;
} else {
this.tail = node;
}
}
};
Queue.prototype.dequeue = function() {
var node = this.head;
if (node !== null) {
this.head = this.head.next;
return node.val;
}
return null;
};
var queue = new Queue();
queue.enqueue(5);
queue.enqueue(6);
queue.enqueue(7);
console.log(queue.dequeue());
console.log(queue.dequeue());
console.log(queue.dequeue());
console.log(queue.dequeue());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment