1. Basic operation of the stack
functionStack () {//using arrays to save stack elements varItems = []; //add a new element to the top of the stack (equivalent to the end of the array) This. Push =function(Element) {Items.push (element); }; //removes the element at the top of the stack and returns the element that was removed This. Pop =function() { returnItems.pop (); }; //returns the element at the top of the stack without making any modifications to the stack This. Peek =function() { returnItems[items.length-1]; }; //Returns true if there are no elements in the stack, otherwise false This. IsEmpty =function() { returnItems.length = = 0; }; //Remove all elements from the stack This. Clear =function() {Items= []; }; //returns the number of elements in the stack, as well as the length of the array. This. Size =function() { returnitems.length; }; //returns the contents of the stack This. Print =function() { //return items.tostring (); returnitems; }; }
Use this method:
varstack =NewStack (); Console.log (Stack.isempty ()); //trueStack.push (1); Stack.push (3); Stack.push (5); Stack.push (7); Console.log (Stack.peek ()); //7Console.log (Stack.print ());//[1, 3, 5, 7]Console.log (Stack.isempty ());//falseConsole.log (Stack.size ());//4Console.log (Stack.pop ()); //7Console.log (Stack.peek ());//5Console.log (Stack.print ());//[1, 3, 5]
2. Convert decimal number to binary number based on this method
//decimal conversion to binary functionDivideBy2 (decnumber) {varRemstack =NewStack (), REM, binarystring= ' '; while(Decnumber > 0) {REM= Math.floor (decnumber% 2); Remstack.push (REM); Decnumber= Math.floor (DECNUMBER/2); } while(!Remstack.isempty ()) {binarystring+=Remstack.pop (). toString (); } returnbinarystring; } varDecnumber = 10; Console.log (Decnumber+ ' converted to binary number: ' + divideBy2 (decnumber));//10 Convert to binary number: 1010
3. The conversion of decimal number to two/eight/16 binary based on this method
//decimal conversion to any binary functionBaseconverter (Decnumber, base) {varRemstack =NewStack (), REM, basestring= ' ', digits= ' 0123456789ABCDEF '; while(Decnumber > 0) {REM= Math.floor (decnumber%base); Remstack.push (REM); Decnumber= Math.floor (Decnumber/base); } while(!Remstack.isempty ()) {basestring+=Digits[remstack.pop ()]; } returnbasestring; } varDecnumber = 552; varBase = 16; Console.log (Decnumber+ ' converted to ' + base + ' binary number: ' + baseconverter (Decnumber, base));//552 conversion to 16 binary number is: 228
Using JavaScript to implement stacks