Queue

Queue

by scotp71

HTML

<h1>
Queue 
</h1>
<br/>

<input type="textbox" id="v" value="" />
<input type="button" value="Enter number" onclick="addNode()"/>


<br/>
<input type="button" value="Calculate Primes" onclick="dequeueNode()"/>
<p id="out"></p>
<div id="output2"></div>

JavaScript

function LinkedList(){
	this.first = null;
  this.last = null;
  this.length = 0;
}

function Node(){
	this.next = null;
  this.prev = null;
  this.content = null;
}

LinkedList.prototype.enqueue = function(_content) {
	var node = new Node();
  node.content = _content;
  if(this.first == null) {
  	this.first = node; 
    this.last = node;
    this.length = 1;
    return node;
  }
  else if(this.first != null){
  	this.last.prev = node;
    node.next = this.last;
    this.last = node;
    this.length++;
    return node;
  }
  
}
LinkedList.prototype.dequeue = function(){
while(this.first!=null){
	var node = new Node();
  node = this.first;
  this.first = this.first.prev;
  this.length--;
  return node.content;
}
return;
}

LinkedList.prototype.print = function() {
	if (this.first == null) return
  var s = "";
  var node = this.first;
  while (node != null) {
  	s += node.content + ", ";
    node = node.prev;
  }  
	return s;
}


var Q1 = new LinkedList();
var Q2 = new LinkedList();

function addNode() {
	//debugger;
  var val = document.getElementById("v").value;
  var start = 2;
  while(start<=val){
  	Q1.enqueue(start);
    start +=1;
  }
  document.getElementById("out").innerHTML = "Iteration 0: Q1 = " + Q1.print();
 
}

function dequeueNode(){
  var text = "";
  var i = 1;
  //var val = document.getElementById("v").value;
  var x = Q1.dequeue();
  Q2.enqueue(x);
  var queueLength = Q1.length;
  var start = 0;
  var end = Q1.length;
  	while(Q1.length>1){
    	while(start!=end){
  			var checkNum = Q1.dequeue();
  			if(checkNum % x !== 0){
  				Q1.enqueue(checkNum);
  			}
    		start++;
      	queueLength = Q1.length;
      }
      text += "Iteration " + i + ": Q1 = " + Q1.print() + "Q2 = " + Q2.print() + "<br>";
 
    document.getElementById("output2").innerHTML = text;
   	i++;
    x=Q1.dequeue();
    Q2.enqueue(x);
    queueLength=Q1.length;
    start=queueLength;
    }
    while(Q1.length==1){
    	text += "Iteration " + i + ": Q1 = " + Q1.print() + "Q2...