力扣细节题:回文链表

注意中间节点的寻找

复制代码
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;
}
相关推荐
203号居民7 小时前
LeetCode hot 100 —41. 缺失的第一个正数
数据结构·算法·leetcode
evans在进步9 小时前
LeetCode 322:零钱兑换——Java 动态规划详解
java·leetcode·动态规划
Tisfy11 小时前
LeetCode 3471.找出最大的几近缺失整数:三种情况判断
算法·leetcode·题解·分类讨论
青 春 记 忆15 小时前
LeetCode 121. 买卖股票的最佳时机|Python 解法详解
python·算法·leetcode
rannn_11115 小时前
【力扣hot100】二叉树专题
算法·leetcode·职场和发展
Navigator_Z17 小时前
LeetCode //C - 1203. Sort Items by Groups Respecting Dependencies
c语言·算法·leetcode
Scabbards_1 天前
面试Leetcode - Heap 堆
java·leetcode·面试
ValhallaCoder1 天前
Leetcode-hot100(2026.08.17)
python·算法·leetcode
青 春 记 忆2 天前
LeetCode 104. 二叉树的最大深度|Python 解法详解
python·算法·leetcode
evans在进步2 天前
LeetCode 198:打家劫舍——Java 动态规划详解
java·leetcode·动态规划