JavaScript栈的实现和回文判断

1. JavaScript栈的实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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;
};
}

2. Stack实现回文判断

1
2
3
4
5
6
7
8
9
10
11
12
13
14
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;
}

3. 结果

1
2
console.log("abcd is Palindrome : " + isPalindrome("abcd"));
console.log("abcdcba is Palindrome : " + isPalindrome("abcdcba"));

说明

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

坚持原创技术分享,您的支持将鼓励我继续创作!