Given a singly linked list, determine if it is a palindrome.
Input: 1->2
Output: false
Input: 1->2->2->1
Output: true
/**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
/**
* @param {ListNode} head
* @return {boolean}
*/
//var isPalindrome = function(head) {
var isPalindrome = function(head) {
let list = [];
for (; head != null;){ //linked list를 순환하며 배열에 담는다
list.push(head.val);
head = head.next;
}
if (list.length<=1) { // 한개일때는 true
return true;
}
for (i = 0; i <= (list.length / 2) >> 0; i++){ // 대칭적으로 비교해보면 되서 n/2 만큼 순환
if (i > (list.length - 1 - i)) { // 양끝에서 부터 좁혀오던 인덱스가 뒤바뀐경우(길이가 짝수인경우 뒤바뀔수 있음)
break;
}
if (list[i] != list[list.length - 1 - i]) { // 대칭 인덱스 값이 다른 경우
return false;
}
}
return true;
};
~.~