栈是什么?

image-20200428222025214

我们要实现的是:

image-20200428222538650

先建立一个Html引入js

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>TEST</title>
<script src="./01_栈.js"></script>
</head>
<body>
</body>
</html>

栈操作.js

//栈的操作

let Stack = function(){
let arr = []

//插入元素到栈底
this.push = (element)=> {
return arr.push(element)
}

//拿出栈顶元素
this.pop = ()=>{
return arr.pop()
}

//查看栈顶
this.peek = ()=>{
return arr[arr.length - 1]
}

//是否为空栈
this.isEmpty = ()=>{
return arr.length == 0
}

//清空栈
this.clear = ()=>{
arr = []
}

//查看栈所有元素
this.getAll = ()=>{
return arr
}

//查看栈元素数量
this.size = ()=>{
return arr.length;
}
}


实际应用:

十进制转二进制
let TtoT = function(numbers){
var stack = new Stack()
let result = ""
while(numbers>0){
let temp = numbers % 2
stack.push(temp)
numbers = (numbers/2)|0
}
while(!stack.isEmpty()){
result+=stack.pop()
}
return result
}