Created
February 15, 2017 07:47
-
-
Save momoci99/085f8daf48957326a3b0d4193ad8f1e3 to your computer and use it in GitHub Desktop.
자바스크립트 + node.js 와 함께하는 자료구조와 알고리즘 - 스택 stack 회문판독기
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Stack 클래스 | |
//Stack 생성자 정의 | |
function Stack() { | |
//스택의 요소가 저장되는 배열 | |
this.dataStore = []; | |
//스택의 위치 | |
this.top = -1; | |
//함수정의 | |
this.push = push; | |
this.pop = pop; | |
this.peek = peek; | |
this.clear = clear; | |
this.length = length; | |
} | |
//스택에 요소를 추가 | |
function push(element) { | |
this.top = this.top + 1; | |
this.dataStore[this.top] = element; | |
} | |
//스택의 꼭대기의 요소를 반환한다. | |
//단 top이 감소하는것은 아니다. | |
function peek() { | |
return this.dataStore[this.top]; | |
} | |
//스택 최상층의 요소를 반환한다. | |
function pop() { | |
//Stack underflow | |
if (this.top <= -1) { | |
console.log("Stack underflow!!!"); | |
return; | |
} | |
else { | |
var popped = this.dataStore[this.top]; | |
//top을 1 감소시킨다. | |
this.top = this.top - 1; | |
return popped; | |
} | |
} | |
//스택의 전체 요소를 삭제한다. | |
function clear() { | |
this.top = -1; | |
} | |
//스택에 저장된 데이터 수 | |
function length() { | |
return this.top + 1; | |
} | |
//스택 클래스 구현 테스트 | |
//회문 판별 코드 | |
function isPalindrome(word) { | |
var stackObj = new Stack(); | |
//전달받은 문자열을 한글자씩 스택에 push() 한다. | |
for (var i = 0; i < word.length; i++) { | |
stackObj.push(word[i]); | |
} | |
//스택에서 꺼낸 문자열이 저장될 변수 | |
var reversed_Word = ""; | |
//스택이 비워질때까지 pop() 수행 | |
while (stackObj.length() > 0) { | |
reversed_Word = reversed_Word + stackObj.pop(); | |
} | |
//원래 전달받은 문자열과 거꾸로 뒤집어진 문자열과 비교 | |
if (word == reversed_Word) { | |
return true; | |
} | |
else { | |
return false; | |
} | |
} | |
var word = "hello"; | |
if(isPalindrome(word)){ | |
console.log(word+" is a palindrome"); | |
} | |
else{ | |
console.log(word+" is not a palindrome"); | |
} | |
word = "racecar" | |
if(isPalindrome(word)){ | |
console.log(word+" is a palindrome"); | |
} | |
else{ | |
console.log(word+" is not a palindrome"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment