Stacks in JavaScript

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.