Data Structure - Stack

A stack is a first-in, first-out data structure. The stack is divided into the bottom of the stack and the top of the stack. The elements added or to be deleted are stored at the end of the stack, that is, the top of the stack. The other end is the bottom of the stack. For example, a stack of books or a stack of plates has the same structure as a stack, and the ones that go in later always come out first.

First, we create a class to represent the stack. Start with the skeleton and slowly add methods to it.

function stacks(){};

Then we choose a way to save the elements in the stack, we can choose the array

var arr = [];

Then we introduce some methods of stack: 1. push(Elements) Add one or more elements to the top of the stack

               2. pop( ) removes the top element of the stack and returns this element

               3. peek( ) returns the element at the top of the stack (does not make any modifications to the stack)

               4. isEmpty( ) judges whether a stack is an empty stack, if it is, it returns true, otherwise it returns false

               5. clear( ) removes all elements in the stack

               6. size( ) is similar to the length attribute of an array, returning the number of elements in the stack

Now let's implement the above methods:

 1、 this.push=function(element){

    arr.push(element)

    }           

 2、 this.pop=function(){

    return arr.pop()

    }

 3、 this.peek=function(){

    return arr[arr.length-1]

    }

 4、 this.isEmpty=function(){

    return arr.length==0

    }

 5、 this.clear=function(){

     arr=[ ]

    }

 6、 this,size=function(){

    return arr.length

    }

The method of the stack has been written here, put the method into the skeleton created at the beginning, and then a complete stack is completed!

function stacks(){

var arr = [];

this.push=function(element){

    arr.push(element)

    };           

this.pop=function(){

    return arr.pop()

    };

this.peek=function(){

    return arr[arr.length-1]

    };

this.isEmpty=function(){

    return arr.length==0

    };

this.clear=function(){

     arr=[ ]

    };

this.size=function(){

    return arr.length

    };

}

Now use this function var fn=new stacks()

           fn.push(10)//Push the number 10

          fn.size()//return the number 1

          fn.clear()//Clear the element

          fn.isEmpty()//Check if it is empty, return true

The other methods will not be tried one by one, and in this way, we have created a complete stack method. There is also the conversion from decimal to binary, if you are interested, you can take a deeper look.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325259267&siteId=291194637