LeetCode 234. 回文链表

class Solution {
public:
    ListNode* reverse(ListNode* head)//翻转以head为头节点的链表
    {
        if(!head||!head->next)  return head;
        auto a=head,b=head->next;
        while(b)
        {
            auto c=b->next;
            b->next=a;
            a=b;
            b=c;
        }
        head->next=nullptr;
        return a;
    }
    bool isPalindrome(ListNode* head) {
        if(!head||!head->next)  return head;
        auto slow=head,quick=head;
        while(quick->next&&quick->next->next)//快慢指针查找中点
        {
            slow=slow->next;
            quick=quick->next->next;
        }
        //此时slow指向中点
        auto r=reverse(slow->next),l=head;
        slow->next=NULL;
        while(l&&r)
        {
            if(l->val!=r->val)  return false;
            l=l->next;
            r=r->next;
        }
        return true;
    }
};
posted @   穿过雾的阴霾  阅读(3)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
点击右上角即可分享
微信分享提示