力扣细节题:回文链表

注意中间节点的寻找

复制代码
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;
}
相关推荐
TracyCoder1231 小时前
LeetCode Hot100(34/100)——98. 验证二叉搜索树
算法·leetcode
We་ct3 小时前
LeetCode 56. 合并区间:区间重叠问题的核心解法与代码解析
前端·算法·leetcode·typescript
努力学算法的蒟蒻6 小时前
day79(2.7)——leetcode面试经典150
算法·leetcode·职场和发展
2401_841495646 小时前
【LeetCode刷题】二叉树的层序遍历
数据结构·python·算法·leetcode·二叉树··队列
2401_841495646 小时前
【LeetCode刷题】二叉树的直径
数据结构·python·算法·leetcode·二叉树··递归
我是咸鱼不闲呀6 小时前
力扣Hot100系列19(Java)——[动态规划]总结(上)(爬楼梯,杨辉三角,打家劫舍,完全平方数,零钱兑换)
java·leetcode·动态规划
铉铉这波能秀7 小时前
LeetCode Hot100数据结构背景知识之列表(List)Python2026新版
数据结构·leetcode·list
仟濹8 小时前
算法打卡 day1 (2026-02-06 周四) | 算法: DFS | 1_卡码网98 可达路径 | 2_力扣797_所有可能的路径
算法·leetcode·深度优先
YuTaoShao9 小时前
【LeetCode 每日一题】1653. 使字符串平衡的最少删除次数——(解法一)前后缀分解
算法·leetcode·职场和发展
VT.馒头9 小时前
【力扣】2727. 判断对象是否为空
javascript·数据结构·算法·leetcode·职场和发展