判断链表回文

题目:

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;
    }
};
相关推荐
Eward-an12 分钟前
LeetCode 76. 最小覆盖子串(详细技术解析)
python·算法·leetcode·职场和发展
guygg8815 分钟前
基于ADMM的MRI-PET高质量图像重建算法MATLAB实现
开发语言·算法·matlab
李昊哲小课18 分钟前
Python itertools模块详细教程
数据结构·python·散列表
moonlight030418 分钟前
类加载子系统
java·jvm·算法
baivfhpwxf202324 分钟前
ACS X轴回零程序 项目实战版
网络·数据库·算法
一叶落43837 分钟前
LeetCode 219. 存在重复元素 II(C语言详解)
算法·哈希算法·散列表
像污秽一样40 分钟前
算法设计与分析-习题2.4
数据结构·算法·排序算法
不想看见40441 分钟前
Reverse Bits位运算基础问题--力扣101算法题解笔记
笔记·算法·leetcode
罗湖老棍子1 小时前
【例 2】数星星 Stars(信息学奥赛一本通- P1536)
数据结构·算法·树状数组·单点修改 区间查询
逆境不可逃1 小时前
LeetCode 热题 100 之 394. 字符串解码 739. 每日温度 84. 柱状图中的最大矩形
算法·leetcode·职场和发展