leetcode刷题—回文链表

1.题目:

给定一个链表的 头节点 head ,请判断其是否为回文链表。

如果一个链表是回文,那么链表节点序列从前往后看和从后往前看是相同的。

在这里插入图片描述
进阶:能否用 O(n) 时间复杂度和 O(1) 空间复杂度解决此题?

2.画图理解

在这里插入图片描述

链表的中间结点和反转链表实现方法之前有写过:
链表的中间结点:https://editor.csdn.net/md/?articleId=129284874
反转链表:https://editor.csdn.net/md/?articleId=129309640

3.代码的实现

//链表的中间结点:如果有两个中间结点,则返回第二个中间结点。
struct ListNode* middleNode(struct ListNode* head){
    struct ListNode* slow=head,*fast=head;
    while(fast&&fast->next)
    {
        slow=slow->next;
        fast=fast->next->next;
    }
    return slow;
}


//反转链表
struct ListNode* reverseList(struct ListNode* head){
struct ListNode* cur=head,*newhead=NULL;
    while(cur)
    {
        struct ListNode* next=cur->next;
        cur->next=newhead;
        newhead=cur;

        cur=next;

    }
    return newhead;
}


bool isPalindrome(struct ListNode* head){
    //拿到链表的中间结点
    struct ListNode* mid = middleNode(head);
    //从中间结点开始逆置
    struct ListNode* rhead = reverseList(mid);

    struct ListNode* curhead = head;
    struct ListNode* curRhead = rhead; 
    
    //当curhead 和 curRhead任意一个为空则结束
    while(curhead && curRhead)
    {
        //curhead 和 curRhead不相等时返回false
        if(curhead->val != curRhead->val)
        {
            return false;
        }
        //否则curhead 和 curRhead指向next
        else
        {
            curhead=curhead->next;
            curRhead=curRhead->next;
        }
    }
    //直到curhead 或 curRhead为空还没返回false,则返回true
    return true;
}

完结~

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小卜~

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值