1. 概述
栈结构是一种非常常见的的数据结构,在程序中应用广泛。就比如我们平常所说的基本数据类型存在栈中。
简单描述:栈就是一个盒子,只有一个入口,从入口放入,从入口取出。
如图:
push:入栈
pop: 出栈
从图可知压入栈的顺序123,而出栈顺序只能为321
可知栈的特点:
先进后出,后进先出
2. 封装一个栈
这里以封装一个数组为例
实现方法:push()、pop()、查看栈顶、判断是否为空、获取栈中元素个数、toString
function Stack() {
this.items = [];
// 1.push
Stack.prototype.push = function (item) {
// this.items.push(item)
this.items[this.items.length] = item
}
// 2.pop
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.nums = function () {
return this.items.length;
}
// 6.toString
Stack.prototype.toString = function () {
return this.items.join(' ')
}
}
验证
let sta = new Stack();
sta.push('a');
sta.push('b');
sta.push('c');
sta.push('d');
console.log(sta);
console.log(sta.peek());
console.log(sta.isEmpty());
console.log(sta.nums());
console.log(sta.toString());
3. 实例(十进制转二进制)
分析: 十进制转二进制:除2取余,余数从后往前取
联系: 将余数依次入栈,出栈刚好是从后往前取
<script>
function TentoTwo(num) {
let arr = [];
let newarr = [];
if (num === 0)
arr.push(0)
while (num !== 0) {
arr.push(num % 2)
num = Math.floor(num / 2);
}
while (arr.length > 0) {
newarr.push(arr.pop());
}
console.log(newarr);
}
TentoTwo(25)
</script>