javasript_数据结构和算法_栈

 1 //-----------------------------------存储结构为数组--------------------------------------------
 2 function Stack(){
 3     this.store = [];
 4     this.top = 0;
 5     this.push = push;
 6     this.pop = pop;
 7     this.display = display;
 8     this.length = length;
 9 
10     this.binary_10 = binary_10;
11 }
12 
13 function push(ele){
14     this.store[this.top] = ele;
15     this.top++;  //top指向下一个元素
16 }
17 function pop(){
18     return this.store[--this.top];
19 }
20 function peek(){
21     return this.store[this.top-1];
22 }
23 function length(){
24     return this.top;
25 }
26 function display(){
27     for(var i=this.length()-1; i>-1; i--){
28         console.log(this.store[i]);
29     }
30 }
31 function binary_10(){
32     var sum = 0;
33     var j = 0;
34     for(var i=this.top-1; i>-1; i--){
35         sum += this.store[i] * Math.pow(2,j);
36         j++;
37     }
38     return sum;
39 }
40 var stack = new Stack();
41 var num = '11001001';
42 for(var i=0; i<num.length; i++){
43     stack.push(num[i]);
44 }
45 stack.display();
46 console.log(stack.binary_10());

 

posted @ 2017-01-02 20:40  巫瞅瞅  阅读(209)  评论(0编辑  收藏  举报