栈遵从后进先出原则
就像生活中的放盘子,后放的先拿走
栈也被用在编译器和内存中保存变量、方法调用等
3.1 栈的创建
创建一个类来表示栈
function Stack() {
// 首先需要一种数据结构来保存栈里的元素,可以选择数组
var items = [];
// 接下来,要为栈声明一些方法
/*
push(ele): 添加一个新元素到栈顶
pop(): 移除栈顶元素,并返回被移除的元素
peek(): 返回栈顶元素,不对栈进行操作
isEmpty(): 如果栈里没有元素返回true,否则返回false
clear(): 移除栈里的所有元素
size(): 返回栈里的元素个数
*/
// push方法
this.push = function(ele) {
items.push(ele);
};
// pop方法
this.pop = function() {
return items.pop();
};
// peek方法
this.peek = function() {
return items[items.length - 1];
};
// isEmpty方法
this.isEmpty = function() {
return items.length === 0;
};
// clear方法
this.clear = function() {
// items.length = 0; // 保留了数组其他属性
items = []; // 更高效
};
// size方法
this.size = function() {
return items.length;
};
// 最后实现一个辅助方法print打印栈的内容
this.print = function() {
console.log(items.toString());
};
}
使用Stack类
var stack = new Stack();
console.log(stack.isEmpty()); // true
stack.push(5);
stack.push(8);
console.log(stack.peek()); // 8
stack.push(11);
console.log(stack.size()); // 3
console.log(stack.isEmpty()); // false
stack.push(15);
利用栈可以实现二进制转换
function divideBy2(decNum) {
var remStack = new Stack(),
rem,
binaryStr = '';
while (decNum > 0) {
rem = Math.floor(decNum % 2);
remStack.push(rem);
decNum = Math.floor(decNum / 2);
}
while (!remStack.isEmpty()) {
binaryStr += remStack.pop().toString();
}
return binaryStr;
}
任意进制的转换
function baseCoverter(decNum, base) {
var remStack = new Stack(),
rem,
str = '',
digits = '0123456789ABCDEF';
while (decNum > 0) {
rem = Math.floor(decNum % base);
remStack.push(rem);
decNum = Math.floor(decNum / 2);
}
while (!remStack.isEmplty()) {
str += digits[remStack.pop()];
}
return str;
}
console.log(baseCoverter(100, 8)); // 144
console.log(baseCoverter(10, 2)); // 1010
console.log(baseCoverter(100345, 16)); // 187F9
※ 以上内容是我在看了js数据结构与算法的时候记录的笔记,仅仅是为了方便查看,哈哈,有需要的小伙伴也可以拿来参考,不用买书了
网友评论