栈结构数组的实现
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
function Stack(){
this.items = []
// 栈的相关操作
// 将元素压入
Stack.prototype.push = function(element){
this.items.push(element)
}
Stack.prototype.pop = function(){
return this.items.pop()
}
Stack.prototype.peek = function(){
return this.items[this.items.length-1]
}
Stack.prototype.isEmpty= function(){
return this.items.length == 0
}
Stack.prototype.size = function(){
return this.items.length
}
Stack.prototype.toString = function(){
var resultString = ''
for(var i=0;i<this.items.length;i++){
resultString+=this.items[i]+''
}
return resultString
}
}
var s = new Stack()
s.push(10)
s.push(20)
alert(s)
s.pop(10)
s.push(50)
s.push(100)
alert(s.peek())
alert(s.isEmpty())
alert(s.size())
alert(s.toString())
</script>
</body>
</html>
栈的应用,十进制转二进制
二进制在计算机中非常重要,计算机里所有内容都是二进制数字表示的
10进制转2进制方法
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
function Stack(){
this.items = []
// 栈的相关操作
// 将元素压入
Stack.prototype.push = function(element){
this.items.push(element)
}
Stack.prototype.pop = function(){
return this.items.pop()
}
Stack.prototype.peek = function(){
return this.items[this.items.length-1]
}
Stack.prototype.isEmpty= function(){
return this.items.length == 0
}
Stack.prototype.size = function(){
return this.items.length
}
Stack.prototype.toString = function(){
var resultString = ''
for(var i=0;i<this.items.length;i++){
resultString+=this.items[i]+''
}
return resultString
}
}
function dec2bin(decNumber){
var stack = new Stack()
while(decNumber>0){
stack.push(decNumber%2)
// 获取整除后的结果作为下一次运算的数字
decNumber= Math.floor(decNumber/2)
}
// 从栈中取出0和1
var binaryString = ''
while(!stack.isEmpty()){
binaryString+=stack.pop()
}
return binaryString
}
alert(dec2bin(100))
alert(dec2bin(10))
alert(dec2bin(1000))
</script>
</body>
</html>