• 1、对栈的操作

    栈是一种特殊的列表,栈内的元素只能通过列表的一端访问,这一端称为栈顶,是一种后入先出的数据结构。

    push() 入栈

    pop()出栈,可以访问栈顶元素,但这个元素删除了

    peek()返回栈顶元素,而不删除

    clear()清除栈内所有元素

    length属性记录栈内元素个数

    top变量用以记录栈顶元素的位置,标记哪里可以加入新元素

    2、栈的实现

    function Stack(){
        this.dataStore = []
        this.top    = 0;
        this.push   = push
        this.pop    = pop
        this.peek   = peek
        this.length = length;
    }
    
    function push(element){
        this.dataStore[this.top++] = element;
    }
    
    function peek(element){
        return this.dataStore[this.top-1];
    }
    
    function pop(){
        return this.dataStore[--this.top];
    }
    
    function clear(){
        this.top = 0
    }
    
    function length(){
        return this.top
    }

     3、数制间的相互转换

    可利用栈将一种数制转换为另一种数制。,假设将数字n转换为以b为基数的数字。

    (1)最高位为n%b,将此位压入栈

    (2)使用n/b代替n.

    (3)重复步骤1和2,直到n等于0,且没有余数

    (4)持续将栈内元素弹出,直到栈为空,依次将这些元素排列,就得到转换后数字的字符

    4、回文

    回文是指一种现象:一个单词、短语或数字,从前往后写和从后往前写都是一样的

    function isPalindrome(word) {
        var s = new Stack()
        for (var i = 0; i < word.length; i++) {
            s.push(word[i])
        }
        var rword = "";
        while (s.length() > 0) {
            rword += s.pop();
        }
        if (word == rword) {
            return true;
        } else {
            return false;
        }
    }
    
    isPalindrome("aarra") //false
    isPalindrome("aaraa") //true

    5、递归

    使用栈来模拟计算5!的过程

    function fact(n) {
        var s = new Stack()
        while (n > 1) {
            //[5,4,3,2]
            s.push(n--);
        }
        var product = 1;
        while (s.length() > 0) {
            product *= s.pop();
        }
        return product;
    }
    
    fact(5) //120
  • 相关阅读:
    Stream 和 byte[] 之间的转换
    C# Process类_进程_应用程序域与上下文之间的关系
    C# Process类_进程管理器Demo
    C# attribute_特性
    SqlDataAdapter类
    SqlDataReader类
    SqlCommand类
    SqlConnection类
    DataTable类
    C# 语法技巧_三目运算_switch_case
  • 原文地址:https://www.cnblogs.com/wwjdx/p/6254130.html
Copyright © 2020-2023  润新知