leetcode:234. 回文链表

题目

给你一个单链表的头节点 head ,请你判断该链表是否为回文链表。如果是,返回 true ;否则,返回 false

示例 1:
[简单] 234. 回文链表 - 图1

  1. 输入:head = [1,2,2,1]
  2. 输出:true

示例 2:
[简单] 234. 回文链表 - 图2

  1. 输入:head = [1,2]
  2. 输出:false

解答 & 代码

  1. /**
  2. * Definition for singly-linked list.
  3. * struct ListNode {
  4. * int val;
  5. * ListNode *next;
  6. * ListNode() : val(0), next(nullptr) {}
  7. * ListNode(int x) : val(x), next(nullptr) {}
  8. * ListNode(int x, ListNode *next) : val(x), next(next) {}
  9. * };
  10. */
  11. class Solution {
  12. private:
  13. // 反转链表
  14. ListNode* reverseNode(ListNode* head)
  15. {
  16. ListNode* pre = nullptr;
  17. ListNode* cur = head;
  18. while(cur != nullptr)
  19. {
  20. ListNode* next = cur->next;
  21. cur->next = pre;
  22. pre = cur;
  23. cur = next;
  24. }
  25. return pre;
  26. }
  27. public:
  28. bool isPalindrome(ListNode* head) {
  29. // 1. 找到链表中点(快慢指针)
  30. ListNode* fast = head;
  31. ListNode* slow = head;
  32. while(fast != nullptr && fast->next != nullptr)
  33. {
  34. fast = fast->next->next;
  35. slow = slow->next;
  36. }
  37. // 最终 slow 就是链表中点
  38. // 若链表长为奇数,则是中间节点;若链表长为偶数,则是第二个中间节点
  39. ListNode* mid = slow;
  40. // 若 fast == nullptr,则链表长为偶数,则 mid 就是右半部分链表的起点
  41. // 若 fast != nulptr,则链表长为奇数,则 mid->next 才是右半部分链表的起点
  42. ListNode* rightHead = fast == nullptr ? mid : mid->next;
  43. // 2. 将右半部分链表进行翻转
  44. rightHead = reverseNode(rightHead);
  45. // 3. 同时遍历左、右两半链表,如果都相同,则原链表是回文链表,否则不是
  46. ListNode* curL = head;
  47. ListNode* curR = rightHead;
  48. while(curR != nullptr)
  49. {
  50. if(curL->val != curR->val)
  51. return false;
  52. curL = curL->next;
  53. curR = curR->next;
  54. }
  55. return true;
  56. }
  57. };

复杂度分析:设链表常委 N

  • 时间复杂度 O(N)
  • 空间复杂度 O(1)

执行结果:

  1. 执行结果:通过
  2. 执行用时:212 ms, 在所有 C++ 提交中击败了 25.31% 的用户
  3. 内存消耗:111.4 MB, 在所有 C++ 提交中击败了 73.00% 的用户