Stack: LIFO. Stack top at the end, bottom of the stack in the front. The newly added element and the element to be deleted are saved at the end of the stack.
Create a stack:
functionStack () {varitems = [];/*Save the elements in the stack with an array*/ This. Push =function(e) {Items.push (e); } This. Pop =function() { returnItems.pop (); } This. Peek =function() { returnItems[length-1]; } This. IsEmpty =function() { returnItems.length = = 0; } This. Size =function() { returnitems.length; } This. Clear =function() {Items= []; } This. Print =function() {Console.log (items.tostring ()); }}
Using the Stack class, instantiate a stack:
var New Stack (); /* Create an empty stack */ /* the way to use it */ stack.size (); // 0Stack.isempty (); // trueStack.push (2); Stack.push (3//"2,3"
What do you do with stacks?
Example: 10 conversion to the specified number of binary numbers.
functionBaseconverter (decnumber,base) {varstack=NewStack (); varRem, binarystring= ' ', digits= ' 0123456789ABCDEF '; while(decnumber>0) {REM=decnumber%Base; Stack.push (REM); Decnumber=math.floor (decnumber/base); } while(!Stack.isempty ()) {binarystring+=Digits[stack.pop ()]; } returnbinarystring;}
JavaScript data structures and algorithms--chapter three stacks