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

示例

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

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

题解

遍历链表,记录到数组中,通过数组翻转判断是否是回文

  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. var arr = []
  14. let p = head
  15. while (p) {
  16. arr.push(p.val)
  17. p = p.next
  18. }
  19. return arr.join('') === arr.reverse().join('')
  20. };

另一种 通过快慢指针找到中间节点,在记录遍历过的翻转节点,对比他们是否同一链表

  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. if (head == null || head.next == null) {
  14. return true
  15. }
  16. let fast = head, slow = head, pre = head, prever = null
  17. while (fast !== null && fast.next !== null) {
  18. pre = slow
  19. fast = fast.next.next
  20. slow = slow.next
  21. pre.next = prever
  22. prever = pre
  23. }
  24. if (fast !== null) {
  25. slow = slow.next
  26. }
  27. while (pre != null && slow != null) {
  28. if (pre.val !== slow.val) {
  29. return false
  30. }
  31. pre = pre.next
  32. slow = slow.next
  33. }
  34. return true
  35. };

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/palindrome-linked-list
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。