This JavaScript Reference section displays the code for an example program that shows how to create a stack in JavaScript.
<!DOCTYPE html> <html> <head> <title>XoaX.net's Javascript</title> <script type="text/javascript" src="Stack.js"></script> </head> <body onload="fnInitialization()"> <p id="idOutput"></p> </body> </html>
// The Link Constructor function CLink(qData) { this.mqData = qData; this.mqpNext = null; } // The LinkedList Constructor function CLinkedList() { this.mqpHead = null; this.mfnInsertAtHead = function(qData) { var qpOldHead = this.mqpHead; this.mqpHead = new CLink(qData); this.mqpHead.mqpNext = qpOldHead; } this.mfnRemoveAtHead = function() { this.mqpHead = this.mqpHead.mqpNext; } this.mfnIsEmpty = function() { return (this.mqpHead == null); } } // The Stack Constructor function CStack() { this.mqList = new CLinkedList(); this.mfnPush = function(qData) { this.mqList.mfnInsertAtHead(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 qStack = new CStack(); 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 qStack.mfnPush(sCurrTribe); } qpPrint.innerHTML += "--------------------------<br />"; // Reverse the printing with a stack while(!qStack.mfnIsEmpty()) { // Take each off the stack and print the value qpPrint.innerHTML += qStack.mfnPop() + "<br />"; } }
© 20072024 XoaX.net LLC. All rights reserved.