栈的定义:
是只允许在一端进行插入或删除的线性表。首先栈是一种线性表,但限定这种线性表只能在某一端进行插入和删除操作。
JavaScript中对栈的封装
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>栈的封装</title>
</head>
<body>
<script>
// Method:和某一个对象实例有联系
// function
// 封装栈类
function Stack() {
// 栈的属性
this.items = []
// 栈的相关操作
// 1.将元素压入栈
Stack.prototype.push = function(element) {
this.items.push(element)
}
// 2.从栈中取出元素
Stack.prototype.pop = function() {
return this.items.pop()
}
// 3.查看下一栈顶元素
Stack.prototype.peek = function() {
return this.items[this.items.length - 1]
}
// 4.判断栈是否为空
Stack.prototype.isEmpty = function() {
return this.items.length == 0
}
// 5.获取栈中元素的个数
Stack.prototype.size = function() {
return this.items.length
}
// 6.toString方法
Stack.prototype.toString = function() {
// 20 10 12 8 7 6
var resultString = ''
for(var i = 0 ; i < this.items.length ; i++) {
resultString += this.items[i]+' '
}
return resultString
}
}
//栈的使用
var s = new Stack()
s.push(20)//20
s.push(10)//20 10
s.push(100)//20 10 100
s.push(200)//20 10 100 200
alert(s)//20 10 100 200
s.pop()//20 10 100
s.pop()//20 10
alert(s.isEmpty())//false
alert(s.size())//2
</script>
</body>
</html>
栈的应用案例-->十进制转二进制
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>十进制转换为二进制栈实现</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))
</script>
</body>
</html>