234. Palindrome Linked List

202408021351
tags: #linked-list

const split = (head) => {
	const dummy = new ListNode();
	dummy.next = head;
	let slow = dummy;
	let fast = dummy;
	while (fast !== null && fast.next !== null) {
	slow = slow.next;
	fast = fast.next.next;
	}
	const rightHalf = slow.next;
	slow.next = null;
	return [head, rightHalf];
}
	
	const reverse = (head) => {
	let cur = head;
	let prev = null;
	while (cur !== null) {
	const then = cur.next;
	cur.next = prev;
	prev = cur;
	cur = then;
	}
	return prev;
}
	
	const isEqual = (l1, l2) => {
	while (l1 !== null && l2 !== null) {
	if (l1.val !== l2.val) {
	return false;
	}
	l1 = l1.next;
	l2 = l2.next;
	}
	return (l1 === null && l2 === null) || (l1.next === null && l2 === null);
	}
	
	var isPalindrome = function(head) {
	if (head === null) {
	return false;
	}
	let [l1, l2] = split(head);
	l2 = reverse(l2);
	return isEqual(l1, l2);
};

Reference