Last active
August 13, 2021 07:04
-
-
Save tpae/42488a621a25847ebe75f59d469a0912 to your computer and use it in GitHub Desktop.
JavaScript implementation of Queue Data Structure
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
// 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