力扣细节题:回文链表

注意中间节点的寻找

复制代码
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;
}
相关推荐
Nil20818 小时前
leetcode 49字母异位分组
算法·leetcode·哈希算法
Nil2081 天前
leetcode 5最长回文子串
算法·leetcode·职场和发展
m0_674571971 天前
力扣 hot 100 python
python·算法·leetcode
圣保罗的大教堂1 天前
leetcode 3727. 最大交替平方和 中等
leetcode
Xin7701 天前
LeetCode 200. 岛屿数量(DFS 深度优先遍历法)
leetcode
alphaTao2 天前
LeetCode 每日一题 2026/10/12-2026/10/18
算法·leetcode
Cccp.1232 天前
【leetcode】(十三)大数据处理
数据结构·算法·leetcode
Pniubi2 天前
力扣70爬楼梯
数据结构·算法·leetcode
Navigator_Z2 天前
LeetCode //C - 1293. Shortest Path in a Grid with Obstacles Elimination
c语言·算法·leetcode
Nil2082 天前
leetcode 64最小路径和
算法·leetcode·职场和发展