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

示例 1:

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

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

利用递归解决

关键点:归的时候是倒序

  1. /**
  2. * Definition for singly-linked list.
  3. * function ListNode(val) {
  4. * this.val = val;
  5. * this.next = null;
  6. * }
  7. */
  8. /**
  9. * @param {ListNode} head
  10. * @return {boolean}
  11. */
  12. var isPalindrome = function(head) {
  13. let left = head
  14. function travese(right){
  15. if(!right) return true
  16. let res = travese(right.next)
  17. if(left.val !== right.val) return false
  18. left = left.next
  19. return res
  20. }
  21. return travese(head)
  22. };