【LeetCode】234. 回文链表

痛定思痛。 2022-05-11 11:22 227阅读 0赞

题目链接:https://leetcode-cn.com/problems/palindrome-linked-list/description/

题目描述

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

示例

输入: 1->2
输出: false

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

进阶:
你能否用 O(n) 时间复杂度和 O(1) 空间复杂度解决此题?

解决方法

思路:把后半段的链表原地反转(反转见第206题),然后和前半段进行比较

  1. /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */
  2. class Solution {
  3. public:
  4. bool isPalindrome(ListNode* head) {
  5. //思路:把后半段的链表原地反转(反转见第206题)然后和前半段进行比较
  6. if (!head || !head->next) return true;
  7. //找到后半段的起点
  8. ListNode* slow=head;
  9. ListNode* fast=head;
  10. while(fast->next && fast->next->next){
  11. slow=slow->next;
  12. fast=fast->next->next;
  13. }
  14. //反转后半段
  15. ListNode *new_head=NULL;
  16. ListNode *temp=NULL;
  17. while(slow){
  18. temp = slow->next;
  19. slow->next = new_head;
  20. new_head = slow;
  21. slow = temp;
  22. }
  23. //前半段与后半段进行比较
  24. while(head && new_head){
  25. if (head->val!=new_head->val) return false;
  26. head=head->next;
  27. new_head=new_head->next;
  28. }
  29. return true;
  30. }
  31. };

发表评论

表情:
评论列表 (有 0 条评论,227人围观)

还没有评论,来说两句吧...

相关阅读