堆??梢杂面湵砗蛿?shù)組兩種方式實(shí)現(xiàn),這里分別給出這兩種實(shí)現(xiàn)方式。
代碼如下:
//數(shù)組實(shí)現(xiàn)
function Stack(){
this.items = [];
this.size = 0;
}
Stack.prototype = {
constructor:Stack,
push:function(data){
this.items[this.size++] = data;
},
pop:function(){
return this.items[--this.size];
},
clear:function(){
this.size = 0;
this.items = [];
},
perk:function(){
return this.items[this.size-1];
}
}
//鏈表實(shí)現(xiàn)
function Stack(){
this.top = null;
this.size = 0;
}
Stack.prototype = {
constructor:Stack,
push:function(data){
var node = {
data:data,
next:null
};
node.next = this.top;
this.top = node;
this.size++;
},
pop:function(){
if(this.top === null){
return null;
}
var out = this.top;
this.top = this.top.next;
if(this.size > 0){
this.size--;
}
return out.data;
},
perk:function(){
return this.top === null ? null:this.top.data;
},
clear:function(){
this.top = null;
this.size = 0;
}
測(cè)試:
var stack = new Stack();
stack.push('k');
stack.push('b');
console.log(stack.perk());//輸出b
stack.pop();
console.log(stack.perk());//輸出k
棧的應(yīng)用
例子:數(shù)值進(jìn)制轉(zhuǎn)換
算法思想如下:
(1) 最高位為 n % b,將此位壓入棧。
(2) 使用 n/b 代替 n。
(3) 重復(fù)步驟 1 和 2,直到 n 等于 0,且沒有余數(shù)。
(4) 持續(xù)將棧內(nèi)元素彈出,直到棧為空,依次將這些元素排列,就得到轉(zhuǎn)換后數(shù)字的字符串形式。
具體代碼實(shí)現(xiàn):
function mulBase(num,base){
var stack = new Stack();
do{
stack.push(num % base);
num = Math.floor(num / base);
}while(num>0);
var result = '';
while(stack.size > 0){
result += stack.pop();
}
return result;
}
console.log(mulBase(234,2)); //輸出11101010
初學(xué)者學(xué)習(xí)筆記,如有不對(duì),還希望高手指點(diǎn)。如有造成誤解,還希望多多諒解。