Last active
January 16, 2018 23:10
-
-
Save MichaelSitter/4f5fa0b414f4530ae60f01e869f95e88 to your computer and use it in GitHub Desktop.
JS data structures - queue
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
'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