[알고리즘] LeetCode - Palindrome Linked List

Jerry·2021년 1월 20일
0

LeetCode

목록 보기
9/73
post-thumbnail

LeetCode - Palindrome Linked List

문제 설명

Given a singly linked list, determine if it is a palindrome.

Example 1

Input: 1->2
Output: false

Example 2

Input: 1->2->2->1
Output: true

Solution

/**
 * 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;
  };

~.~

profile
제리하이웨이

0개의 댓글