解法一
时间复杂度O(n)、空间复杂度O(n)
遍历链表,转化为数组,通过头尾指针向中间靠拢并比对,判断是否是回文
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
|
var isPalindrome = function (head) { if (!head || !head.next) return true; const arr = []; let cur = head; while (cur) { arr.push(cur.val); cur = cur.next; } let left = 0, right = arr.length - 1; while (left <= right) { if (arr[left++] !== arr[right--]) { return false; } } return true; };
|
解法二
时间复杂度O(n)、空间复杂度O(1)
通过快慢指针,定位到链表的中点,反转后续的链表,并于前面的链表比对,判断是否是回文链表
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
|
var isPalindrome = function (head) { if (!head || !head.next) return true; let slow = head, fast = head; while (fast.next && fast.next.next) { slow = slow.next; fast = fast.next.next; } let prev = null, cur = slow.next; slow.next = null; while (cur) { const next = cur.next; cur.next = prev; prev = cur; cur = next; } let p1 = head, p2 = prev; while (p1 && p2) { if (p1.val !== p2.val) { return false; } p1 = p1.next; p2 = p2.next; } return true; };
|