LeetCode 热题 100 JavaScript--234. 回文链表

LeetCode 热题 100 JavaScript--234. 回文链表_第1张图片

function ListNode(val, next) {
  this.val = val === undefined ? 0 : val;
  this.next = next === undefined ? null : next;
}

var isPalindrome = function (head) {
  if (!head || !head.next) {
    return true; 
  }

  // 使用快慢指针法找到链表的中间节点
  let slow = head;
  let fast = head;

  while (fast && fast.next) {
    slow = slow.next;
    fast = fast.next.next;
  }

  // 翻转链表的后半部分
  let prev = null;
  while (slow) {
    let temp = slow.next;
    slow.next = prev;
    prev = slow;
    slow = temp;
  }

  let left = head;
  let right = prev;

  while (right) {
    if (left.val !== right.val) {
      return false; 
    }
    left = left.next;
    right = right.next;
  }

  return true;
};


你可能感兴趣的:(力扣热题100,leetcode,javascript,链表)