判断链表回文

题目:

cpp 复制代码
//方法一,空间复杂度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;
    }
};
相关推荐
姚瑞南20 分钟前
【AI 风向标】四种深度学习算法(CNN、RNN、GAN、RL)的通俗解释
人工智能·深度学习·算法
补三补四42 分钟前
SMOTE 算法详解:解决不平衡数据问题的有效工具
人工智能·算法
RTC老炮1 小时前
webrtc弱网-RobustThroughputEstimator源码分析与算法原理
网络·算法·webrtc
努力努力再努力wz1 小时前
【C++进阶系列】:万字详解智能指针(附模拟实现的源码)
java·linux·c语言·开发语言·数据结构·c++·python
听风吹等浪起1 小时前
分类算法-逻辑回归
人工智能·算法·机器学习
敲代码的嘎仔1 小时前
JavaWeb零基础学习Day2——JS & Vue
java·开发语言·前端·javascript·数据结构·学习·算法
yacolex2 小时前
3.3_数据结构和算法复习-栈
数据结构·算法
茉莉玫瑰花茶2 小时前
动态规划 - 两个数组的 dp 问题
算法·动态规划
微笑尅乐2 小时前
从暴力到滑动窗口全解析——力扣8. 字符串转换整数 (atoi)
算法·leetcode·职场和发展
火花怪怪2 小时前
LaMer结晶动力学模型
算法