apilar en js

estructura de datos de la versión js - operaciones relacionadas de la pila

Una pila es similar a una mesa lineal, pero es una mesa lineal especial que solo se puede operar en un extremo.
La pila es de último en entrar, primero en salir
. Por lo tanto, los elementos solo se pueden tomar de la parte superior de la pila.

 <script>   
        // 栈的封装
        // 用构造函数封装栈
        function Stack() {
    
    
            // 栈中的属性
            this.item = [];
            // 栈的相关处操作
            // 1.将元素压入栈
            Stack.prototype.push = function (element) {
    
    
                this.item.push(element);
            }
            // 2.从栈中取出元素
            Stack.prototype.pop = function () {
    
    
                return this.item.pop(this.item[this.item.length - 1])
            }
            // 3.查看一下栈顶元素
            Stack.prototype.peek = function () {
    
    
                return this.item[this.item.length - 1];
            }
            // 4.判断栈是否为空
            Stack.prototype.isEmpty = function () {
    
    
                return this.item.length == 0;
            }
            // 5.获取栈中元素的个数
            Stack.prototype.size = function () {
    
    
                return this.item.length;
            }
            // 6.toString方法
            Stack.prototype.toString = function () {
    
    
                return this.item.join(' ');
            }
        }
        // 栈的使用
        // var s = new Stack();
        // s.push(2);
        // s.push(5);
        // s.push(1);
        // alert(s.item);
        // alert(s.pop());
        // alert(s.peek());
        // alert(s.isEmpty());
        // alert(s.toString());


        // 函数:将10进制转2进制
        function dec2bin(decNumber) {
    
    
            // 1.定义栈对象
            var stack = new Stack();
            // 2.往栈中加入元素
            while (decNumber > 0) {
    
    
                stack.push(decNumber % 2);
                decNumber = Math.floor(decNumber / 2);
            }
            // 3.把栈里的元素依次取出来
            var str = ''
            while (!stack.isEmpty()) {
    
    
                str += stack.pop();
            }
            return str;
        }
        // 调用进制转换函数并打印
        console.log(dec2bin(100));
        console.log(dec2bin(50));
        console.log(dec2bin(10));
    </script>

Supongo que te gusta

Origin blog.csdn.net/weixin_52797317/article/details/127416781
Recomendado
Clasificación