Skip to main content

回文链表

题目

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

示例

输入: 1 -> 2 -> 2 -> 1

输出: true

题解

和第 143. 重排链表 类似, 先拿到链表的中点, 然后对右半部分反转链表, 最后让两个链表对比即可.

/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} head
* @return {boolean}
*/
var isPalindrome = function (head) {
if (head === null || head.next === null) return true

const mid = midNode(head)
let left = head
let right = reverseList(mid)

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

return true
}

var midNode = function (head) {
let slow = head,
fast = head

while (fast !== null && fast.next !== null) {
fast = fast.next.next
slow = slow.next
}

return slow
}

var reverseList = function (head) {
let prev = null,
curr = head

while (curr) {
const next = curr.next
curr.next = prev
prev = curr
curr = next
}

return prev
}

时间复杂度: O(n)

空间复杂度: O(1)