栈是一种先进后出的数据结构,利用这种数据结构特性能方便实现很多功能,如下代码提供了利用JavaScript实现简单的栈结构,并利用栈去实现判断回文和数制转换。

<script>
        function Stack() {
            this.dataStore=[];
            this.top=0;
            this.push=push;
            this.pop=pop;
            this.peek=peek;
            this.len=length;
            this.clear=clear;
        }

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

        //测试Stack类
//        var s=new Stack();
//        s.push("a");
//        s.push("b");
//        s.push("c");
//        console.log(s.len());
//        console.log(s.pop());
//        console.log(s.pop());
//        console.log(s.pop());
////        console.log(s.peek());

        //利用Stack类实现数值转换
//        function mulBase(num,base) {
//            var s=new Stack();
//            do{
//                s.push(num%base);
//                num=Math.floor(num/=base);
//            }while(num>0);
//
//            var converted="";
//            while(s.len()>0){
//                converted+=s.pop();
//            }
//            return converted;
//        }
//        var num=32;
//        console.log(mulBase(num,16));

        //利用Stack判断回文
        function isPalindrome(word) {
            var s=new Stack();
            var len=word.length;
            for(var i=0;i<len;i++){
                s.push(word[i]);
            }
            var rword="";
            while(s.len()>0){
                rword+=s.pop();
            }
            if(word===rword){
                return true;
            }else{
                return false;
            }
        }
        console.log(isPalindrome("hello"));
        console.log(isPalindrome("abccba"));

    </script>
10-07 15:55