Skip to main content

234. Palindrome Linked List

分析

本题组合了链表相关的多个题目,反转后注意没有连接操作,而是根据更短的 r 来进行while

题解

function isPalindrome(head: ListNode | null): boolean {
const middleNode = getMiddleNode(head)
let r = reverseListNode(middleNode.next)
let l = head

while (r) {
if (l.val !== r.val) {
return false
}
l = l.next
r = r.next
}

return true
};


function getMiddleNode(head: ListNode | null): ListNode | null {
let fast = head, slow = head
while (fast?.next?.next) {
fast = fast.next.next
slow = slow.next
}

return slow
};

function reverseListNode(head: ListNode | null): ListNode | null {
if (!head?.next) {
return head
}
const last = reverseListNode(head.next)
head.next.next = head
head.next = null
return last
}