栈的应用

由于最近有点忙,本打算写些关于栈的特性和实际应用。一直拖到现在才简单的写写。

关于栈的实现见javascript 栈 stack

一、数字进制之间的转换,可以栈实现。如将十进制转换为八进制

            var s = new Stack();
            s.Init();

            function convert(num){
                var str = "";
                while(num!==0){
                    s.Push(num%8);
                    num= parseInt( num/8);
                }
                while(!s.Empty()){
                    str += s.Pop().toString();
                }
                return str;
            }
            
            convert(15);

二、表达式求值

下面的例子只是模拟了将数字添加到数字栈,将字符添加到符号栈中。

            var optr = new Stack();
            optr.Init();
            optr.Push("#");
              
            var opnd = new Stack();
            opnd.Init();
           
            function test(str){
                var i = 0;
                var ch = str.charAt(0);     
                while(str.charAt(i)!=='#'){
                    if(parseInt(ch)>=0&&parseInt(ch)<=9){
                        opnd.Push(ch);
                    }
                    else{
                        optr.Push(ch);
                    }
                    i++;
                    ch = str.charAt(i);
                }
            }  
            
            test("2*(6-3)#");

三、类似表达式求值,将字符串具有一定的意义,如"email-min:6-max:12-empty"。现实与表达式一样,例子没有提供。

原文地址:https://www.cnblogs.com/kuikui/p/2635634.html