PS/LeetCode

LeetCode / Linked List / 234번 / Palindrome Linked List / JS

KimMinJun 2023. 4. 19. 23:47

< 문제 바로가기 >

 

Palindrome Linked List - LeetCode

Can you solve this real interview question? Palindrome Linked List - Given the head of a singly linked list, return true if it is a palindrome or false otherwise.   Example 1: [https://assets.leetcode.com/uploads/2021/03/03/pal1linked-list.jpg] Input: hea

leetcode.com

 

< 문제 간단설명 >

주어진 Linked List가 팰린드롬인지, 즉 앞으로해도 뒤로해도 같은지 판단하는 문제이다.

 

/**
 * 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) {
  let tmp = [];
  while(head) {
      tmp.push(head.val);
      head = head.next;
  }

  return tmp.join('') === tmp.reverse().join('')
};