题目

https://leetcode-cn.com/problems/palindrome-linked-list/

解题

  1. /**
  2. * Definition for singly-linked list.
  3. * function ListNode(val, next) {
  4. * this.val = (val===undefined ? 0 : val)
  5. * this.next = (next===undefined ? null : next)
  6. * }
  7. */
  8. /**
  9. * @param {ListNode} head
  10. * @return {boolean}
  11. */
  12. var isPalindrome = function(head) {
  13. // 思路:将val放到数组中,使用双指针进行判断
  14. const values = []
  15. while(head !== null) {
  16. values.push(head.val)
  17. head = head.next
  18. }
  19. for (let i = 0, j = values.length - 1; i < j; i++, j--) {
  20. if (values[i] !== values[j]) {
  21. return false
  22. }
  23. }
  24. return true
  25. };