Stack
Use case
Computer use stack internally called the call stack.
The example of function call
Actions
- Push: Add a new item to the top
- Pop: Remove the topmost item and read it
function Stack(){
let items = [];
this.push = function(item){
items.push(item);
}
this.pop = function(){
return items.pop();
}
this.peek = function(){
return items[items.length-1];
}
this.isEmpty = function(){
return items.length ==0;
}
this.clear = function(){
items = [];
}
this.size = function(){
return items.length;
}
this.print = function(){
console.log(items.toString());
}
}
let stack = new Stack()
// stack.push(11)
// stack.push(12)
// stack.push(15)
// stack.peek()
// stack.pop()
// stack.pop()
// stack.print()
// console.log(stack.isEmpty())
// console.log(stack.size())
// decimal to binary
function divideBy2(decNumber){
let remStack = new Stack(),rem,binaryString = "";
while(decNumber>0){
rem = Math.floor(decNumber%2);
remStack.push(rem);
decNumber = Math.floor(decNumber/2);
}
while(!remStack.isEmpty()){
binaryString+=remStack.pop().toString();
}
return binaryString;
}
// console.log(divideBy2(1000))
// base converter
function baseConverter(decNumber, base) {
let 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
}
baseConverter(100345,2)
// console.log(baseConverter(100345,2))
Reference:
Hero Picture
comments powered by Disqus