A stack is an ordered collection that adheres to the last-in, first-out (LIFO) principle. It's like a stack of plates.
Push adds an element to the top of the stack
Pop removes and returns the element at the top of the stack
Peek returns the top element of the stack
IsEmpty returns True if there are no elements in the stack, otherwise false.
Clear removes all elements from the stack
Size returns the number of elements
function Stack () { var items=[]; This.push=function (ele) { items.push (ele); } This.pop=function () { return items.pop (); } This.peek=function () { return items[items.length-1]; } This.isempty=function () { return items.length==0; } This.size=function () { return this.length; } This.clear=function () { items=[]; } This.print=function () { console.log (items.tostring ());} }
Convert to Binary
function DivideBy2 (decnumber) { var remstack=new Stack (), 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 (); } return binarystring; }
Convert to any binary
function Baseconverter (decnumber,base) { var remstack=new Stack (), rem,binarystring= "", digits= " 0123456789ABCDEF "; while (decnumber>0) { rem=math.floor (decnumber%base); Remstack.push (REM); Decnumber=math.floor (decnumber/base); } while (!remstack.isempty ()) { binarystring+=digits[remstack.pop ()]; } return binarystring; }
Stacks in JavaScript