Core JavaScript

A Queue

This JavaScript Reference section displays the code for an example program that shows how to create a queue in JavaScript.

Queue.html

<!DOCTYPE html>
<html>
<head>
    <title>XoaX.net's Javascript</title>
    <script type="text/javascript" src="Queue.js"></script>
</head>
<body onload="fnInitialization()">
    <p id="idOutput"></p>
</body>
</html>

Queue.js

// The Link Constructor
function CLink(qData) {
  this.mqData = qData;
  this.mqpNext = null;
}

// The LinkedList Constructor
function CLinkedList() {
  this.mqpHead = null;
  this.mqpTail = null;
  this.mfnInsertAtTail = function(qData) {
	if (this.mqpTail == null) {
		this.mqpHead = new CLink(qData);
		this.mqpTail = this.mqpHead;
	} else {
    	this.mqpTail.mqpNext = new CLink(qData);
    	this.mqpTail = this.mqpTail.mqpNext;
	}
  }
  this.mfnRemoveAtHead = function() {
    this.mqpHead = this.mqpHead.mqpNext;
    if (this.mqpHead == null) {
		this.mqpTail = this.mqpHead;
	}
  }
  this.mfnIsEmpty = function() {
    return (this.mqpHead == null);
  }
}

// The Queue Constructor
function CQueue() {
  this.mqList = new CLinkedList();
  this.mfnPush = function(qData) {
    this.mqList.mfnInsertAtTail(qData);
  }
  this.mfnPop = function() {
	var qPopped = this.mqList.mqpHead;
    this.mqList.mfnRemoveAtHead();
    return qPopped.mqData;
  }
  this.mfnIsEmpty = function() {
    return this.mqList.mfnIsEmpty();
  }
}

function fnInitialization() {
	var saTribes = ["Reuben", "Simeon", "Levi", "Judah", "Issachar",
    "Zebulun", "Dan", "Naphtali", "Gad", "Asher", "Joseph", "Benjamin"];
    var qQueue = new CQueue();
	var qpPrint = document.getElementById("idOutput");
	qpPrint.innerHTML = "";

	// Print the tribes in the order of the array entries.
	for(var sCurrTribe of saTribes){
		qpPrint.innerHTML += sCurrTribe + "<br />";
		// Push each tribe name onto the stack
		qQueue.mfnPush(sCurrTribe);
	}
	qpPrint.innerHTML += "--------------------------<br />";

	// Reverse the printing with a stack
	while(!qQueue.mfnIsEmpty()) {
		// Take each off the stack and print the value
		qpPrint.innerHTML += qQueue.mfnPop() + "<br />";
	}
}
 

Output

 
 

© 2007–2024 XoaX.net LLC. All rights reserved.