使用栈判断回文

Stack.js

function Stack() {
    this.dataStore=[];
    this.push=function (element) {
        this.dataStore[this.dataStore.length]=element;
    }

    this.pop=function(){
        if(this.dataStore.length<1)
            return null;
        //取得最后的数据
        var buffer = this.dataStore[this.dataStore.length-1];
        //把最后的数据置空
        this.dataStore[this.dataStore.length-1]=null;
        //改变数组的长度
        this.dataStore.length--;
        //返回数据
        return buffer;
    }

    this.peek=function () {

        //取得头部数据
        var buffer = this.dataStore[0];
        //获得数组的长度
        var length = this.dataStore.length;
        //遍历数据
        for(var i=0;i<length-1;i++){
            //把数据往前面移动
            this.dataStore[i]=this.dataStore[i+1];
        }
        //把最后的数据置空
        this.dataStore[length-1]=null;
        //数组的长度减少
        this.dataStore.length--;
        //返回数据
        return buffer;
    }

    this.length = function () {
        return this.dataStore.length;
    }

    this.clear=function () {
        delete this.dataStore;
        this.dataStore=[];
    }

    this.forEach=function (call) {
        //1,获得数组的长度
        var length = this.dataStore.length;
        //2,遍历数据
        for(var i=length-1;i>=0;i--){
            // var item= this.dataStore[i];
            call(this.dataStore[i]);
        }
    }

}

HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="Stack.js"></script>
</head>
<body>

</body>
<script>
    String.prototype.forEach = function (call) {
        for(var i=0;i<this.length;i++) {
            call(this[i]);
        }
    }

    function isPalindrome(data) {
        var stack = new Stack();
        data.forEach(function (item) {
            stack.push(item);
        });

        var buffer = '';
        stack.forEach(function (word) {
            buffer = buffer+word
        });
        if(buffer==data)
            return true;
        else
            return false;
    }

    console.log(isPalindrome("aabbaa"));
</script>
</html>

猜你喜欢

转载自blog.csdn.net/qq_34607371/article/details/81104288