力扣细节题:回文链表

注意中间节点的寻找

复制代码
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;
}
相关推荐
ʚ希希ɞ ྀ3 分钟前
leeCode hot 100 !!!持续更新中
数据结构·算法·leetcode
剪一朵云爱着6 分钟前
力扣1539. 第 k 个缺失的正整数
算法·leetcode
吃着火锅x唱着歌5 小时前
LeetCode 2016.增量元素之间的最大差值
数据结构·算法·leetcode
元亓亓亓7 小时前
LeetCode热题100--46. 全排列--中等
算法·leetcode·职场和发展
墨染点香7 小时前
LeetCode 刷题【146. LRU 缓存】
leetcode·缓存·哈希算法
qk学算法7 小时前
力扣滑动窗口题目-76最小覆盖子串&&1234替换子串得到平衡字符串
数据结构·算法·leetcode
小欣加油7 小时前
leetcode 860 柠檬水找零
c++·算法·leetcode·职场和发展·贪心算法
还是码字踏实7 小时前
基础数据结构之数组的矩阵遍历:螺旋矩阵(LeetCode 54 中等题)
数据结构·leetcode·矩阵·螺旋矩阵
im_AMBER10 小时前
算法笔记 10
笔记·学习·算法·leetcode
夏鹏今天学习了吗18 小时前
【LeetCode热题100(59/100)】分割回文串
算法·leetcode·深度优先