js 数据结构学习之栈
- 实例:二进制转换
divide(decNumber,base){
const items = new WeakMap();
class Stack {
constructor(){
items.set(this, []);
}
push(element){
let s = items.get(this);
s.push(element);
}
pop(){
let s = items.get(this);
let r = s.pop();
return r;
}
peek(element){
let s = items.get(this);
return s[s.length -1];
}
isEmpty(element){
let s = items.get(this);
return s.length == 0;
}
size(element){
let s = items.get(this);
return s.length;
}
clear(element){
let s = items.get(this);
s = [];
}
print(element){
let s = items.get(this);
console.log(s.toString());
}
}
var remStack = new Stack(),rem,baseString = '',digits = '0123456789ABCDEF';
while(decNumber > 0){
rem = Math.floor(decNumber % base);
remStack.push(rem);
decNumber = Math.floor(decNumber / base);
}
while(!remStack.isEmpty()){
baseString += digits[remStack.pop()];
}
return baseString;
}
学贵有恒,而行胜于言