题目链接

题目描述

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

示例

示例1:

输入: 1->2 输出: false

思路

思路1:数组+双指针

将链表的值存到数组中,使用双指针判断是否是回文。

思路2:迭代

使用快慢指针将链表平分,将后半部分反转,再判断是否是回文。
注:最好不要修改原链表的结构,若修改,再返回前再修改回来。

题解

思路1:数组+双指针

  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. public:
  13. bool isPalindrome(ListNode* head) {
  14. vector<int> vec;
  15. while (head) {
  16. vec.emplace_back(head->val);
  17. head = head->next;
  18. }
  19. int left = 0, right = vec.size() - 1;
  20. while (left < right) {
  21. if (vec[left] != vec[right]) {
  22. return false;
  23. }
  24. ++left;
  25. --right;
  26. }
  27. return true;
  28. }
  29. };

思路2:迭代

  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. ListNode* splitList(ListNode* head) {
  14. ListNode* fast = head;
  15. ListNode* slow = head;
  16. while (fast->next != nullptr && fast->next->next != nullptr) {
  17. fast = fast->next->next;
  18. slow = slow->next;
  19. }
  20. return slow;
  21. }
  22. ListNode* reverseList(ListNode* head) {
  23. ListNode* prev = nullptr;
  24. ListNode* curr = head;
  25. ListNode* next = nullptr;
  26. while (curr) {
  27. next = curr->next;
  28. curr->next = prev;
  29. prev = curr;
  30. curr = next;
  31. }
  32. return prev;
  33. }
  34. public:
  35. bool isPalindrome(ListNode* head) {
  36. if (head == nullptr) {
  37. return true;
  38. }
  39. ListNode* firstPartTail = splitList(head);
  40. ListNode* secondPartHead = reverseList(firstPartTail->next);
  41. ListNode* p1 = head;
  42. ListNode* p2 = secondPartHead;
  43. bool ret = true;
  44. while (p2) {
  45. if (p1->val != p2->val) {
  46. ret = false;
  47. break;
  48. }
  49. p1 = p1->next;
  50. p2 = p2->next;
  51. }
  52. firstPartTail->next = reverseList(secondPartHead);
  53. return ret;
  54. }
  55. };

复杂度分析

思路1:数组+双指针

  • 时间复杂度:0234-回文链表 - 图1
  • 空间复杂度:0234-回文链表 - 图2

    思路2:迭代

  • 时间复杂度:0234-回文链表 - 图3

  • 空间复杂度:0234-回文链表 - 图4