js版数据结构----栈的相关操作
栈和线性表类似,但是是特殊的线性表,只能在一端操作
栈后进先出
因此,只能从栈顶开始取元素元素
<script>
// 栈的封装
// 用构造函数封装栈
function Stack() {
// 栈中的属性
this.item = [];
// 栈的相关处操作
// 1.将元素压入栈
Stack.prototype.push = function (element) {
this.item.push(element);
}
// 2.从栈中取出元素
Stack.prototype.pop = function () {
return this.item.pop(this.item[this.item.length - 1])
}
// 3.查看一下栈顶元素
Stack.prototype.peek = function () {
return this.item[this.item.length - 1];
}
// 4.判断栈是否为空
Stack.prototype.isEmpty = function () {
return this.item.length == 0;
}
// 5.获取栈中元素的个数
Stack.prototype.size = function () {
return this.item.length;
}
// 6.toString方法
Stack.prototype.toString = function () {
return this.item.join(' ');
}
}
// 栈的使用
// var s = new Stack();
// s.push(2);
// s.push(5);
// s.push(1);
// alert(s.item);
// alert(s.pop());
// alert(s.peek());
// alert(s.isEmpty());
// alert(s.toString());
// 函数:将10进制转2进制
function dec2bin(decNumber) {
// 1.定义栈对象
var stack = new Stack();
// 2.往栈中加入元素
while (decNumber > 0) {
stack.push(decNumber % 2);
decNumber = Math.floor(decNumber / 2);
}
// 3.把栈里的元素依次取出来
var str = ''
while (!stack.isEmpty()) {
str += stack.pop();
}
return str;
}
// 调用进制转换函数并打印
console.log(dec2bin(100));
console.log(dec2bin(50));
console.log(dec2bin(10));
</script>