Next I'll try to use JavaScript to implement common data structures, and write stacks today.
The first thing we need to know is that the stack is an ordered set that follows the last-in, first-out (LIFO) principle. The newly added or deleted elements are saved at the 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 close to the bottom. In JavaScript, variable saving and function calls are stored in stacks.
A class is first created to represent a stack, and a data structure is required to hold the elements in the stack. Here we select the array to hold the data inside the stack: var array = [];
Note that at this point the end of the array is equivalent to the top of the stack.
Next, declare some methods for our stack:
- Push (): Add a new Element (or several) to the top of the stack
- Pop (): Removes the element at the top of the stack and returns the element that was removed
- Peek (): Gets the element at the top of the stack and does not make any modifications to the stack
- IsEmpty (): Returns True if there are no elements in the stack, otherwise false
- Clear (): Empty stack
- Size (): Returns the number of stack elements
functionStack () {vararray = [];//defines an internal array used to store data, simulating the top of the stack with the end of the array This. Push =function(data) {//adding elements to the top of the stackArray.push (data); } This. Pop =function(){//remove top of stack element returnArray.pop (); } This. IsEmpty =function(){//determine if the stack is empty if(Array.Length = = 0){ return true; } return false; } This. Peek =function(){//returns the element at the top of the stack returnArray[array.length-1]; } This. Clear =function(){//clears the elements in the stackArray = []; } This. Size =function(){//returns the number of elements in the stack returnArray.Length; } This. Print =function(){//elements of the print stackConsole.log (array.tostring ()); }}varstack =NewStack ();//Instantiate the StackStack.push ("haha");//adding elementsStack.push ("Lala"); Console.log (Stack.isempty ()); //See if the stack is emptyConsole.log (Stack.peek ());//returns the element at the top of the stackConsole.log (Stack.size ());//returns the number of elements in the stackStack.print ();//elements of the print stackStack.clear ();//clears the elements of the stackConsole.log (Stack.isempty ());//See if the stack is empty at this time
The following is an example of a test that was instantiated in Chrome's console and the results were correct.
The stack of JavaScript data structures.