力扣细节题:回文链表

注意中间节点的寻找

复制代码
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;
}
相关推荐
梭七y9 小时前
【力扣hot100题】(103)移动零
数据结构·算法·leetcode
Jeremy爱编码10 小时前
leetcode热题腐烂的橘子
算法·leetcode·职场和发展
alphaTao10 小时前
LeetCode 每日一题 2025/12/22-2025/12/28
算法·leetcode
小白菜又菜11 小时前
Leetcode 1523. Count Odd Numbers in an Interval Range
算法·leetcode
小白菜又菜12 小时前
Leetcode 944. Delete Columns to Make Sorted
算法·leetcode
Swift社区14 小时前
LeetCode 458 - 可怜的小猪
算法·leetcode·职场和发展
Dream it possible!15 小时前
LeetCode 面试经典 150_分治_将有序数组转换为二叉搜索树(105_108_C++_简单)(递归)
c++·leetcode·面试
Q741_14715 小时前
C++ 栈 模拟 力扣 227. 基本计算器 II 题解 每日一题
c++·算法·leetcode·模拟
im_AMBER15 小时前
Leetcode 88 K 和数对的最大数目
数据结构·c++·笔记·学习·算法·leetcode
nju_spy16 小时前
12月力扣每日一题(划分dp + 单调栈 + 堆 + 会议安排)
算法·leetcode·二分查找·动态规划·滑动窗口·单调栈·最大堆