判断链表回文

题目:

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;
    }
};
相关推荐
粉色挖掘机40 分钟前
矩阵在密码学的应用——希尔密码详解
线性代数·算法·机器学习·密码学
七七七七071 小时前
【计算机网络】UDP协议深度解析:从报文结构到可靠性设计
服务器·网络·网络协议·计算机网络·算法·udp
TitosZhang1 小时前
排序算法稳定性判断
数据结构·算法·排序算法
一种乐趣2 小时前
PHP推荐权重算法以及分页
算法·php·推荐算法
ccLianLian2 小时前
计算机视觉·TagCLIP
人工智能·算法
千弥霜2 小时前
codeforces1997(div.3)E F
算法
周杰伦_Jay3 小时前
【Python后端API开发对比】FastAPI、主流框架Flask、Django REST Framework(DRF)及高性能框架Tornado
数据结构·人工智能·python·django·flask·fastapi·tornado
利刃大大3 小时前
【动态规划:01背包】01背包详解 && 模板题 && 优化
c++·算法·动态规划·力扣·背包问题
im_AMBER3 小时前
算法笔记 10
笔记·学习·算法·leetcode
workflower3 小时前
FDD与其他方法的相似和区别
数据库·算法·需求分析·个人开发