当前位置:   article > 正文

[数据结构]-链表回文结构判断_回文检测数据结构

回文检测数据结构

目录

回文结构判断

一、中间结点

二、链表翻转

三、全部代码


回文结构判断

对于一个链表,请设计一个时间复杂度为O(n),额外空间复杂度为O(1)的算法,判断其是否为回文结构。

给定一个链表的头指针A,请返回一个bool值,代表其是否为回文结构。保证链表长度小于等于900。

测试样例:1->2->2->1          return:true

                  1->2->3->2->1     return:true

                  1->2->4->3          return:false

原题目:链表的回文结构_牛客题霸_牛客网 (nowcoder.com)

分为以下两种情况讨论,只需要找到中间结点,然后记录中间结点地址并翻转。将反转后的链表和原链表进行比较即可判断原链表是否为回文。



一、中间结点

 首先来讲解一下如何使用一次遍历来找到单链表的中间结点。

用到了常见的双指针,其中分别为快指针慢指针。快指针一次遍历两个结点,慢指针一次遍历一个结点。

具体代码如下:

  1. //找出中间结点
  2. struct ListNode* MiddleNode(struct ListNode* head)
  3. {
  4. struct ListNode* fast = head;
  5. struct ListNode* slow = head;
  6. //快指针为NULL或快指针的下一个节点为NULL跳出循环
  7. while( fast && fast->next )
  8. {
  9. slow = slow->next;
  10. fast = fast->next->next;
  11. }
  12. return slow;
  13. }

二、链表翻转

 接下来讲解如何使用反转链表。

此时需要三指针,需要记录当前节点的前一结点当前结点和当前结点的下一结点

具体代码如下:

  1. //对中间结点开始的链表进行翻转
  2. struct ListNode* reverseList(struct ListNode* head)
  3. {
  4. struct ListNode* cur = head;
  5. struct ListNode* newhead = NULL;
  6. struct ListNode* next;
  7. while(cur)
  8. {
  9. next = cur->next;
  10. //头插法
  11. cur->next = newhead;
  12. newhead = cur;
  13. cur = next;
  14. }
  15. return newhead;
  16. }

三、全部代码

  1. /*
  2. struct ListNode {
  3. int val;
  4. struct ListNode *next;
  5. ListNode(int x) : val(x), next(NULL) {}
  6. };*/
  7. class PalindromeList {
  8. public:
  9. //找出中间结点
  10. struct ListNode* MiddleNode(struct ListNode* head)
  11. {
  12. struct ListNode* fast = head;
  13. struct ListNode* slow = head;
  14. while( fast && fast->next )
  15. {
  16. slow = slow->next;
  17. fast = fast->next->next;
  18. }
  19. return slow;
  20. }
  21. //对中间结点开始的链表进行翻转
  22. struct ListNode* reverseList(struct ListNode* head)
  23. {
  24. struct ListNode* cur = head;
  25. struct ListNode* newhead = NULL;
  26. struct ListNode* next;
  27. while(cur)
  28. {
  29. next = cur->next;
  30. //头插法
  31. cur->next = newhead;
  32. newhead = cur;
  33. cur = next;
  34. }
  35. return newhead;
  36. }
  37. bool chkPalindrome(ListNode* A)
  38. {
  39. struct ListNode* cur = A;
  40. struct ListNode* Middle = MiddleNode(A);
  41. struct ListNode* New = reverseList(Middle);
  42. while(cur && New)
  43. {
  44. if(cur->val != New->val)
  45. return false;
  46. cur = cur->next;
  47. New = New->next;
  48. }
  49. return true;
  50. }
  51. };

本文内容由网友自发贡献,转载请注明出处:https://www.wpsshop.cn/w/从前慢现在也慢/article/detail/934808
推荐阅读
相关标签
  

闽ICP备14008679号