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
- Push (value): Add a new element to the top of the stack
- Pop (): Removes the element from the top of the stack and returns the element
- Peek (): Gets the element at the top of the stack
- IsEmpty (): Determines whether the stack is empty. Yes returns True, no return fallse
- Clear (): Clears the elements in the stack
- 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