棧結構數組的實現

棧結構數組的實現

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script>
     function Stack(){
        this.items = [] 
        // 棧的相關操作
        // 將元素壓入
        Stack.prototype.push = function(element){
            this.items.push(element)
        }
        Stack.prototype.pop = function(){
            return this.items.pop()
        }
        Stack.prototype.peek = function(){
            return this.items[this.items.length-1]
        }
        Stack.prototype.isEmpty= function(){
            return this.items.length == 0
        }
        Stack.prototype.size = function(){
            return this.items.length
        }
        Stack.prototype.toString = function(){
            var resultString = ''
            for(var i=0;i<this.items.length;i++){
                resultString+=this.items[i]+''
            }
            return resultString
        }


     }
     var s = new Stack()
     s.push(10)
     s.push(20)
     alert(s)
     s.pop(10)
     s.push(50)
     s.push(100)
     alert(s.peek())
     alert(s.isEmpty())
     alert(s.size())
     alert(s.toString())
    </script>
</body>
</html>

棧的應用,十進制轉二進制
二進制在計算機中非常重要,計算機裏所有內容都是二進制數字表示的
10進制轉2進制方法

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script>
    function Stack(){
        this.items = [] 
        // 棧的相關操作
        // 將元素壓入
        Stack.prototype.push = function(element){
            this.items.push(element)
        }
        Stack.prototype.pop = function(){
            return this.items.pop()
        }
        Stack.prototype.peek = function(){
            return this.items[this.items.length-1]
        }
        Stack.prototype.isEmpty= function(){
            return this.items.length == 0
        }
        Stack.prototype.size = function(){
            return this.items.length
        }
        Stack.prototype.toString = function(){
            var resultString = ''
            for(var i=0;i<this.items.length;i++){
                resultString+=this.items[i]+''
            }
            return resultString
        }


     }
        function dec2bin(decNumber){
            var stack = new Stack()
            while(decNumber>0){
                stack.push(decNumber%2)
                // 獲取整除後的結果作爲下一次運算的數字
                decNumber= Math.floor(decNumber/2)
            }
            // 從棧中取出0和1
            var binaryString = ''
            while(!stack.isEmpty()){
                binaryString+=stack.pop()
            }
            return binaryString
        }
        alert(dec2bin(100))
        alert(dec2bin(10))
        alert(dec2bin(1000))
    </script>
</body>
</html>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章