判断链表回文

题目:


//方法一,空间复杂度O(n)
class Solution {
public:
    bool isPalindrome(ListNode* head) {
        vector<int> nums;      //放进数组后用双指针判断
        ListNode* cur = head;
        while(cur){
            nums.emplace_back(cur->val);
            cur = cur->next;
        }
        for(int i=0, j=nums.size()-1; i < j; i++, j--){
            if(nums[i]!=nums[j]) return false;
        }
        return true;
    }
};
//方法二,空间复杂度O(1)
class Solution {
public:
    bool isPalindrome(ListNode* head) {
        if(!head) return true;
        ListNode* end = findend(head);
        ListNode* head1 = reverseList(end->next);
        ListNode* cur1 = head;
        ListNode* cur2 = head1;
        while(cur1&&cur2){
            if(cur1->val!=cur2->val) return false;
            cur1 = cur1->next;
            cur2 = cur2->next;
        }
        end->next = reverseList(head1);  //恢复链表
        return true;
    }
    //寻找链表前半部分的末尾节点
    ListNode* findend(ListNode* head){
        ListNode* slow = head;
        ListNode* fast = head;
        while(fast->next&&fast->next->next){
            fast = fast->next->next;
            slow = slow->next;
        }
        return slow;
    }
  //翻转链表
   ListNode* reverseList(ListNode* head){
        ListNode* pre = nullptr;
        ListNode* cur = head;
        ListNode* tmp;
        while(cur){
            tmp = cur->next;
            cur->next = pre;
            pre = cur;
            cur = tmp;
        }
        return pre;
    }
};

相关推荐

  1. Leetcode234.判断是否是

    2024-03-11 07:40:05       22 阅读
  2. leetcode-

    2024-03-11 07:40:05       65 阅读
  3. 234.

    2024-03-11 07:40:05       39 阅读
  4. 234.

    2024-03-11 07:40:05       35 阅读
  5. 234.

    2024-03-11 07:40:05       33 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-03-11 07:40:05       98 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-03-11 07:40:05       106 阅读
  3. 在Django里面运行非项目文件

    2024-03-11 07:40:05       87 阅读
  4. Python语言-面向对象

    2024-03-11 07:40:05       96 阅读

热门阅读

  1. 【spring】-多模块构建

    2024-03-11 07:40:05       37 阅读
  2. 3488.最短路径floyd、并查集

    2024-03-11 07:40:05       37 阅读
  3. Lua 函数前的冒号和点号,你知道他们的区别吗?

    2024-03-11 07:40:05       44 阅读
  4. [2023年]-hadoop面试真题(一)

    2024-03-11 07:40:05       48 阅读
  5. C/C++关键字详解-----`const`的使用

    2024-03-11 07:40:05       46 阅读
  6. Spring Boot(六十六):集成Alibaba Druid 连接池

    2024-03-11 07:40:05       47 阅读
  7. API 管理调研

    2024-03-11 07:40:05       38 阅读
  8. pytorch单机多卡训练 logger日志记录和wandb可视化

    2024-03-11 07:40:05       42 阅读
  9. Apache 的安装与目录结构

    2024-03-11 07:40:05       48 阅读
  10. 【Docker】apache 容器化部署

    2024-03-11 07:40:05       50 阅读
  11. Apache Hive(三)

    2024-03-11 07:40:05       43 阅读