栈是一种遵从后进先出(LIFO)原则的有序集合。新添加的或待删除的元素都保存在栈的
同一端,称作栈顶,另一端就叫栈底。在栈里,新元素都靠近栈顶,旧元素都接近栈底。
- 栈是限定仅在表的一端进行插入和删除操作的线性表。
- 栈顶,top of the stack
- 栈底,bottom of the stack
- 栈为空时,称为空栈
- 栈的插入操作,也叫做进栈、入栈或压栈
- 栈的删除操作,也叫做出栈或弹栈
封装类
function Stack() {
this.items = [];
}
Stack.prototype.push = function (element) {
this.items.push(element);
return this.items.length;
};
//出栈
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.clear = function () {
this.items = [];
};
//打印栈中的所有元素
Stack.prototype.print = function () {
// console.log(this.items.toString());
let str = "";
this.items.reduce(function (prev, current) {
str += current + " ";
}, "");
return str;
};
应用
var stack = new Stack();
stack.push(1);
stack.push(2);
stack.push(3);
stack.push(4);
stack.push(5);
console.log(stack.print());
console.log(stack.pop());
stack.push(30)
console.log(stack.print());
实战演练
利用栈去完成数据进制的转化
1.10进制转二进制
//十进制转化为二进制
const nums = divide2Binary(10);
const nums2 = divide2Binary(233);
const nums3 = divide2Binary(1000);
console.log("🚀 ~ nums:", nums)
console.log("🚀 ~ nums:", nums2)
console.log("🚀 ~ nums:", nums3)
function divide2Binary(number){
//一个栈
var stack = new Stack();
while(number > 0){
const rem = number % 2;
stack.push(rem);
number = Math.floor(number / 2);
}
console.log(stack.print());
//栈倒序
var result = [];
while(stack.size() > 0){
result.push(stack.pop())
}
return result.join("")
}
2.10进制转任意进制
const d1 = convert(10,2);
const d2 = convert(233,2);
const d3 = convert(100345,8)
console.log(d1);
console.log(d2);
console.log(d3);
//进制转化
function convert(number, base){
//一个栈
var stack = new Stack();
const string = "0123456789ABCDEF";
while(number > 0){
const rem = number % base;
stack.push(string[rem]);
number = Math.floor(number / base);
}
//栈倒序
var result = [];
while(stack.size() > 0){
result.push(stack.pop())
}
return result.join("")
}
这样就实现的栈的封装与使用