数据结构之栈(Stack)的实现/封装与应用–JavaScript
1.基于数组实现Stack栈的封装
<!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 = []
// 栈的相关操作
// this.push = function () {
// }
// 进栈
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
}
// toString方法
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(20)
// s.push(10)
// s.push(100)
// alert(s)
// s.pop()
// alert(s)
// s.peek()
// alert(s.toString())
/****************************/
</script>
</body>
</html>
2.栈(Stack)的应用---------十进制数转化为二进制数
// 十进制转化为二进制函数
function dec2bin(decNumber){
var stack = new Stack()
while(decNumber > 0){
stack.push(decNumber%2)
decNumber = Math.floor(decNumber / 2)
}
var binaryString = ''
while(!stack.isEmpty()){
binaryString += stack.pop()
}
return binaryString
}
/**********测试代码**************/
// alert(dec2bin(100))
// alert(dec2bin(8))
/*******************************/

本文介绍如何使用JavaScript实现栈(Stack)的数据结构,并封装相关操作如push、pop等。同时,通过栈实现十进制数到二进制数的转换,提供具体代码示例及测试。
268

被折叠的 条评论
为什么被折叠?



