Native JS implementation Stack structure

Source: Internet
Author: User

1. Preface

Stack, is an ordered collection that adheres to the LIFO (lifo,later-in-first-out) principle. The newly added elements are stored at one end of the stack, called the top of the stack, and the other end is called the bottom of the stack. In the stack, the new elements are near the top of the stack, and the old elements are near the bottom.

2. Function description
    1. Push (value): Add a new element to the top of the stack
    2. Pop (): Removes the element from the top of the stack and returns the element
    3. Peek (): Gets the element at the top of the stack
    4. IsEmpty (): Determines whether the stack is empty. Yes returns True, no return fallse
    5. Clear (): Clears the elements in the stack
    6. Size (): Gets the number of elements in the stack
3. Code implementation

First, create a class to represent the stack, and initialize an empty array to hold the elements in the stack

class Stack {    constructor () {      this. Items = [];    };  } 

Next, implement the required functionality in this stack class:

class Stack {constructor () { This. Items = [];    }; Push (value) { This. Items.push (value);    }; Pop () {return  This. Items.pop ();    }; Peek () {return  This. items[ This. items.length-1];    }; IsEmpty () {return  This. Items.length = = 0;    }; Clear () {return  This. Items = [];    }; Size () {return  This. Items.length; }  }
4. Testing
var New Stack (); Stack.push (5); Stack.push (6); Stack.push (7); Console.log (Stack.pop ()) ; Console.log (Stack.peek ()); Console.log (Stack.isempty ()); Console.log (Stack.size ()); Console.log (Stack.clear ()); Console.log (Stack.size ()); Console.log (stack);

Finish

Native JS implementation stack structure

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.