Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

javascript数据结构--栈(2018.01.03) #15

Open
aermin opened this issue Feb 13, 2018 · 0 comments
Open

javascript数据结构--栈(2018.01.03) #15

aermin opened this issue Feb 13, 2018 · 0 comments

Comments

@aermin
Copy link
Owner

aermin commented Feb 13, 2018

数组是计算机科学中最常用的数据结构,栈和队列类似数组,但 添加和删除元素时更为可控。

栈(stack)是一种后进先出原则的有序集合。(如一摞书,后放进去的先拿出来)
栈

function Stack() {
    //用一种数据结构保存栈里的元素,这里选择数组
    var items = []; 
    //添加一个一个或几个元素到栈顶
    this.push = function(element){
        items.push(element);
    };
    //移除栈顶的元素,同时返回被移出的元素
    this.pop = function(){
        return items.pop();
    };
   //返回栈顶的元素,不对栈做任何修改
    this.peek = function(){
        return items[items.length-1];
    };
    //栈里没元素返回true 有就返回false
    this.isEmpty = function(){
        return items.length == 0;
    };
    //返回栈里的个数
    this.size = function(){
        return items.length;
    };
    //移除栈里所有元素
    this.clear = function(){
        items = [];
    };
    //打印
    this.print = function(){
        console.log(items.toString());
    };
    //数组转字符串
    this.toString = function(){
        return items.toString();
    };
}

使用

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

十进制到二进制

function divideBy2(decNumber){

var remStack = new Stack(), 
      rem, 
      binaryString = '';

while (decNumber > 0){ //{1}
     rem = Math.floor(decNumber % 2); //{2}       
     remStack.push(rem); //{3}
     decNumber = Math.floor(decNumber / 2); //{4} 
}

while (!remStack.isEmpty()){ //{5} 
      binaryString  = remStack.pop().toString(); 
}

return binaryString;

}

使用 (测试时记得把上面封装的Stack函数带上)

divideBy2(10);  // "1010"

十转二进制

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant