棧遵從后進(jìn)先出原則
就像生活中的放盤子,后放的先拿走
棧也被用在編譯器和內(nèi)存中保存變量、方法調(diào)用等
3.1 棧的創(chuàng)建
創(chuàng)建一個(gè)類來表示棧
function Stack() {
// 首先需要一種數(shù)據(jù)結(jié)構(gòu)來保存棧里的元素,可以選擇數(shù)組
var items = [];
// 接下來,要為棧聲明一些方法
/*
push(ele): 添加一個(gè)新元素到棧頂
pop(): 移除棧頂元素,并返回被移除的元素
peek(): 返回棧頂元素,不對(duì)棧進(jìn)行操作
isEmpty(): 如果棧里沒有元素返回true,否則返回false
clear(): 移除棧里的所有元素
size(): 返回棧里的元素個(gè)數(shù)
*/
// 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; // 保留了數(shù)組其他屬性
items = []; // 更高效
};
// size方法
this.size = function() {
return items.length;
};
// 最后實(shí)現(xiàn)一個(gè)輔助方法print打印棧的內(nèi)容
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);
利用棧可以實(shí)現(xiàn)二進(jìn)制轉(zhuǎn)換
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;
}
任意進(jìn)制的轉(zhuǎn)換
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
※ 以上內(nèi)容是我在看了js數(shù)據(jù)結(jié)構(gòu)與算法的時(shí)候記錄的筆記,僅僅是為了方便查看,哈哈,有需要的小伙伴也可以拿來參考,不用買書了