基本概念
栈(Stack)是一种后进先出的结构,LIFO(Last In First Out)
实现栈方法
Stack class
class Stack {constructor() {this.stack = []this.top = 0}}
push()
栈尾部推入一个元素,top指针自增
push(element) {this.stack.push(element);this.top++;}
pop()
top指针自减,移除元素并返回移除元素
pop() {if (this.top !== 0) {this.top--;return this.stack.pop();}return 'Stack is empty';}
peek()
返回顶部元素的值
peek() {if (this.top !== 0) {return this.stack[this.top - 1];}return null;}
size()
返回当前栈的大小
size() {return this.top;}
isEmpty()
返回当前栈是否为空
isEmpty() {return this.top === 0;}
clear()
清空栈
clear() {while (this.top > 0) {this.pop();}}
封装栈结构
class Stack {constructor() {this.stack = []this.top = 0}// Add element to the end of the stackpush(element) {this.stack.push(element);this.top++;}// Return and remove the last element of the stackpop() {if (this.top !== 0) {this.top--;return this.stack.pop();}return 'Stack is empty';}// Return the last element of the stack without removingpeek() {if (this.top !== 0) {return this.stack[this.top - 1];}return null;}// Return true if stack is empty, flase otherwiseisEmpty() {return this.top === 0;}// Return the number of elements in the stacksize() {return this.top;}// Clear stack elementsclear() {// this.item = [];while (this.top > 0) {this.pop();}}}
场景应用
- 十进制转二进制
