判断链表回文

题目:

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;
    }
};
相关推荐
乐迪信息16 分钟前
乐迪信息:基于AI算法的煤矿作业人员安全规范智能监测与预警系统
大数据·人工智能·算法·安全·视觉检测·推荐算法
hsjkdhs1 小时前
C++之多层继承、多源继承、菱形继承
开发语言·c++·算法
立志成为大牛的小牛1 小时前
数据结构——十七、线索二叉树找前驱与后继(王道408)
数据结构·笔记·学习·程序人生·考研·算法
星空下的曙光1 小时前
Node.js crypto模块所有 API 详解 + 常用 API + 使用场景
算法·node.js·哈希算法
Algo-hx1 小时前
数据结构入门 (七):从“链接”到“分支” —— 初探树与二叉树
数据结构
小贾要学习2 小时前
【数据结构】C++实现红黑树
数据结构·c++
StarPrayers.3 小时前
旅行商问题(TSP)(2)(heuristics.py)(TSP 的两种贪心启发式算法实现)
前端·人工智能·python·算法·pycharm·启发式算法
爱吃橘的橘猫3 小时前
嵌入式系统与嵌入式 C 语言(2)
c语言·算法·嵌入式
235163 小时前
【LeetCode】146. LRU 缓存
java·后端·算法·leetcode·链表·缓存·职场和发展
weixin_307779134 小时前
使用Python高效读取ZIP压缩文件中的UTF-8 JSON数据到Pandas和PySpark DataFrame
开发语言·python·算法·自动化·json