栈
- 相对于数组在删除和添加数据的时候更为可控
- 先进后出,后进先出
这个像落书一样,后落上去的书,先拿下去
栈的数据结构
- 栈
- push:添加栈顶
- pop:移除栈顶
- peek:但会栈顶元素
- isEmpty:是否为空
- clear:晴空万里
- size:大小
// es5
function Stack(){
let items= []
this.push=function(elements){
items.push(elements)
}
this.pop=function(){
return items.pop();
}
this.peek=function(){
return items[items.length-1]
}
this.isEmpty=function(){
return items.length == 0
}
this.size=function(){
return items.length
}
this.clear=function(){
items = []
}
this.print=function(){
console.log(items.toString())
}
}
现在都2020年了es6多少得摸一下
// es6 会暴露iterm
/*
* 节省内存
* 会暴露iterm,不能私有化,可被操作
*/
class Stack{
constructor(){
this.items=[]
}
push(elements){
this.items.push(elements)
console.log(this.items.toString())
}
}
_items = Symbol()
class Stack{
constructor(){
this._items=[]
}
push(elements){
this._items.push(elements)
console.log(this.items.toString())
}
}
栈能解决问题
- 回溯问题(后面说)
- 进制转化实例
// 转二进制
function divideBy2(decNumber){
let stack = new Stack(),
binaryString=''
while(decNumber>0){
stack.push(Math.floor(decNumber % 2))
decNumber = Math.floor(decNumber / 2)
console.log(decNumber)
}
while(!stack.isEmpty()){
binaryString += stack.pop().toString()
}
return binaryString
}
// 转任意进制
// 突然发现这东西可以做加密🔐
function baseConverter(decNumber,base=2){
let stack = new Stack(),
baseString='',
digits='0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ+/'
while(decNumber>0){
stack.push(Math.floor(decNumber%base))
decNumber=Math.floor(decNumber/base)
}
while(!stack.isEmpty()){
baseString+=digits[stack.pop()]
}
return baseString
}
以后遇到栈解决的题会在下面补充👏👏👏