JavaScript 数据结构 — 栈
一,栈的基本操作
1,push(elemenet):压栈,添加一个新元素到栈顶位置
2,pop():出栈,移除栈顶元素,同时返回被移除的元素
3, peek():返回栈顶元素,不对栈做任何修改(这个方法不会移除栈顶元素,仅仅返回它)
4,isEmpty():(empty:空的)栈为空,返回true,栈不为空,返回false
5,size():返回栈里元素个数,与数组中的length方法类似
6,toString():将栈结构的内容以字符串的形式返回
二,封装栈
function Stack() {
//栈中的属性
this.item = [],
//栈的相关操作
//push
Stack.prototype.push = function (element) {
this.item.push(element);
}
Stack.prototype.pop = function () {
return this.item.pop();
}
Stack.prototype.peek = function () {
return this.item[this.item.length - 1];
}
Stack.prototype.isEmpty = function () {
return this.item.length === 0;
}
Stack.prototype.size = function () {
return this.item.length;
}
Stack.prototype.toString = function () {
let resultString = '';
for (let i = 0; i < this.item.length; i++) {
resultString += this.item[i] += " ";
}
return resultString;
}
}
三,测试
var s = new Stack();
s.push(10);
s.push(20);
s.push(30);
s.push(80);
console.log(s.toString()); //10 20 30 80
s.pop();
console.log(s.toString()); //10 20 30
console.log(s.peek()); //30
console.log(s.isEmpty()); //false
console.log(s.size()); //3
四,例:应用栈将十进制转二进制
function decToBin(decNumber) {
//1,定义一个栈对象
var stack = new Stack();
//2,循环操作
while (decNumber > 0) {
//2.1获取余数,并将余数压入栈中
stack.push(decNumber % 2);
//2.2获取整除后的结果,作为下一次运行的数字
decNumber = Math.floor(decNumber / 2);
}
//3,从栈中取出0和1
var binaryString = "";
while (!stack.isEmpty()) {
binaryString += stack.pop();
}
return binaryString;
}
//测试十进制转二进制的函数
var num = 1000;
console.log(decToBin(num));