Skip to content

Latest commit

 

History

History
45 lines (39 loc) · 847 Bytes

0234-回文链表.md

File metadata and controls

45 lines (39 loc) · 847 Bytes

请判断一个链表是否为回文链表。

示例 1:

输入: 1->2 输出: false 示例 2:

输入: 1->2->2->1 输出: true 进阶: 你能否用 O(n) 时间复杂度和 O(1) 空间复杂度解决此题?

var isPalindrome = function(head) {
  if (!head) return true
  let slow = head
  let fast = head
  while(fast.next && fast.next.next) {
    fast = fast.next.next
    slow = slow.next
  }
  let prev = null
  let cur = slow.next
  while(cur) {
    let nextTemp = cur.next
    cur.next = prev
    prev = cur
    cur = nextTemp
  }

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

解题思路: 用快慢指针截取一半的链表后反转一部分链表,再对比,这题难度不像是简单