/* * @Description: 234. Palindrome Linked List * @Author: libk * @Github: https://github.com/libk */ /** * 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} */ const isPalindrome = function (head) { if (head === null || head.next === null) { returntrue } let fast = head let slow = head while (fast !== null && fast.next !== null) { slow = slow.next fast = fast.next.next }
// 如果fast不是null,说明链表节点的个数是奇数个 if (fast !== null) { slow = slow.next } slow = reverseList(slow) fast = head while (slow !== null) { if (slow.val !== fast.val) { returnfalse } slow = slow.next fast = fast.next } returntrue }
functionreverseList (head) { if (head === null || head.next === null) { return head } let pre = null let cur = head while (cur !== null) { let temp = cur.next cur.next = pre pre = cur cur = temp } return pre }