LeetCode-234. Palindrome Linked List

问题描述

Given the head of a singly linked list, return true if it is a palindrome.

Constraints:

  • The number of nodes in the list is in the range [1, 105].
  • 0 <= Node.val <= 9

Follow up: Could you do it in O(n) time and O(1) space?

解答

找到链表的后半部分,将后半部分反转,再跟前半部分比较

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
/*
* @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) {
return true
}
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) {
return false
}
slow = slow.next
fast = fast.next
}
return true
}

function reverseList (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
}