Spring 2017 Exam Question 11
by Robert Mochel
HTML
<input type="textbox" id='input' />
<br>
<input type='button' value='Add' onclick='addToQueue();' />
<input type='button' value='Remove' onclick='removeFromQueue();' />
<br/>
<div id='output'></div>
JavaScript
//Question 11
function Node(content) {
this.content = content;
this.next = null;
}
function Queue() {
this._length = 0;
this.head = null;
}
Queue.prototype.enqueue = function(content) {
var node = new Node(content),
currentNode = this.head;
if (!currentNode) {
this.head = node;
this._length++;
return node;
}
while (currentNode.next) {
currentNode = currentNode.next;
}
currentNode.next = node;
this._length++;
};
Queue.prototype.dequeue = function() {
temp = this.head;
this._length--;
this.head = this.head.next;
return temp.content;
}
Queue.prototype.print = function() {
var string = ' ';
var current = this.head;
while (current) {
string += current.content + "<br>";
current = current.next;
}
return string;
}
var q = new Queue;
function removeFromQueue() {
var t = document.getElementById("input").value;
q.dequeue(t);
document.getElementById("output").innerHTML = q.print();
}
function addToQueue() {
var t = document.getElementById("input").value;
q.enqueue(t);
document.getElementById("output").innerHTML = q.print();
}