力扣细节题:回文链表

注意中间节点的寻找

复制代码
struct ListNode* reverseList(struct ListNode* head){
    if(!head) return NULL;
  struct ListNode*cur=head;
  struct ListNode*pre=NULL;
  struct ListNode*next;
    while(cur){
        next=cur->next;
        cur->next=pre;
        pre=cur;
        cur=next;
    
    }
    return pre;
}//将链表原地逆置

bool isPalindrome(struct ListNode* head){
    struct ListNode *p,*q;
    if(!head||!head->next) return true;
    //若单链表只有一个或为空则为回文链表
    p=head;
    q=head->next;
    while(q->next){
        p=p->next;
        q=q->next;
        if(q->next)
            q=q->next; 
    }
    q=p->next;  //此时p指向链表中点,q指向链表后半段的第一个结点
    q=reverseList(q);
    p=head;
    while(q){
        if(p->val!=q->val)
            return false;
        p=p->next;
        q=q->next;
    }
    return true;
}
相关推荐
科大饭桶2 小时前
数据结构自学Day5--链表知识总结
数据结构·算法·leetcode·链表·c
YuTaoShao4 小时前
【LeetCode 热题 100】24. 两两交换链表中的节点——(解法一)迭代+哨兵
java·算法·leetcode·链表
前端拿破轮5 小时前
翻转字符串里的单词,难点不是翻转,而是正则表达式?💩💩💩
算法·leetcode·面试
凤年徐5 小时前
【数据结构与算法】203.移除链表元素(LeetCode)图文详解
c语言·开发语言·数据结构·算法·leetcode·链表·刷题
李昊_6 小时前
【LeetCode 3440. 重新安排会议得到最多空余时间 II】解析
算法·leetcode
呆呆的小鳄鱼6 小时前
leetcode:322. 零钱兑换[完全背包]
算法·leetcode·职场和发展
এ᭄画画的北北7 小时前
力扣-240.搜索二维矩阵 II
算法·leetcode·矩阵
JJ1M87 小时前
前缀和+贪心总结,基于每日一题力扣3439、3440
python·算法·leetcode
呆呆的小鳄鱼7 小时前
leetcode:518. 零钱兑换 II[完全背包]
算法·leetcode·职场和发展
沧澜sincerely8 小时前
二分查找【各种题型+对应LeetCode习题练习】
算法·leetcode·二分查找