/**
* 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 slow = head, fast = head, pre = null;
// 使用快慢指针找到链表的中点,同时反转前半部分链表
while (fast && fast.next) {
fast = fast.next.next;
// 反转链表的前半部分
let next = slow.next; // 暂存下一个节点
slow.next = pre; // 将当前节点的 next 指向前一个节点
pre = slow; // pre 向前移动
slow = next; // slow 向前移动
}
// 如果链表长度是奇数,跳过中间节点
if (fast) {
slow = slow.next;
}
// 比较反转后的前半部分和后半部分
while (pre && slow) {
if (pre.val !== slow.val) {
return false;
}
pre = pre.next;
slow = slow.next;
}
return true;
};
/**
* @param {ListNode} head
* @return {boolean}
*/
var isPalindrome = function(head) {
if(!head || !head.next){
return true
}
let arr = []
while(head){
arr.push(head.val)
head = head.next
}
for(let i=0,j=arr.length-1; i<j; i++,j--){
if(arr[i] !== arr[j]){
return false
}
}
return true
}
原创文章,作者:czhdawn,如若转载,请注明出处:https://www.czhdawn.cn/archives/4916
