JavaScript栈的实现和回文判断

来源:互联网 发布:clasence 软件 编辑:程序博客网 时间:2024/05/16 16:25

JavaScript栈的实现:

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

Stack实现回文判断:

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

function isPalindrome(word) {  if (word === "")return true;  if (!word)return false;  var s = new Stack;  var len = word.length, curr_index = 0;  while (curr_index < len) {    s.push(word[curr_index++]);  }  var newWord = '';  while (s.top != 0) {    newWord += s.pop();  }  return newWord == word;}
console.log("abcd is Palindrome : " + isPalindrome("abcd"));console.log("abcdcba is Palindrome : " + isPalindrome("abcdcba"));
0 0
原创粉丝点击