Palindrome Linked List
Description
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
Follow up:
Could you do it in O(n) time and O(1) space?
Solution(javascript)
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} head
* @return {boolean}
*/
const isPalindrome = (head) => {
const reverse = (head) => {
const aux = (current, acc) => {
if (!current) {
return acc
}
acc = {
val: current.val,
next: acc,
}
return aux(current.next, acc)
}
return aux(head, null)
}
const reversed = reverse(head)
const compare = (c1, c2) => {
if (!c1) {
return true
}
if (c1.val === c2.val) {
return compare(c1.next, c2.next)
}
return false
}
return compare(head, reversed)
}