Stack structure application

The rules of the stack

  • The stack follows the last in first out rule
  • The new element comes in is called pushing the new element onto the top of the stack
  • Deletion is called unstacking, removing the top element of the stack
  • Like the buffet tray in life, the last one is always taken away first

Function call stack

  • Function A calling function B pushes function B to the top of the stack, and A to the bottom of the stack
  • B will not be ejected from the stack until its execution is complete. In this case, B will call C and C will be pushed to the top of the stack
  • The current order is bottom of stack A > B > top of stack C
  • After C is executed, the stack is displayed, and the sequence is C > B > A
  • Recursion is called all the time and cannot be ejected from the stack, thus causing stack overflow

The interview questions

There are 6 elements, 6/5/4/3/2/1, which of the following is not a valid unstack order ()

A. 5 4 3 6 1 2 B. 4 5 3 2 1 6 C. 3 4 6 5 2 1 D. 2 3 4 1 5 6

Stack structure implementation

The stack of encapsulation

Function Stack() {this.items = []} const s = new Stack() s.istems.push () s.istems.pop () / /...Copy the code

The use of the stack

// Convert base 10 to base 2
function to2(parms) {
  let stk = []
  while (parms > 0) {
    stk.push(parms % 2)
    parms = Math.floor(parms / 2)}let str = ""
  while(stk.length ! = =0) {

    str += stk.pop()
  }
  return str
}
console.log(to2(100))
Copy the code