力扣细节题:回文链表

注意中间节点的寻找

复制代码
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;
}
相关推荐
_fairyland4 小时前
数据结构 力扣 练习
数据结构·考研·算法·leetcode
橘颂TA4 小时前
【剑斩OFFER】算法的暴力美学——山脉数组的蜂顶索引
算法·leetcode·职场和发展·c/c++
博语小屋5 小时前
力扣11.盛水最多的容器(medium)
算法·leetcode·职场和发展
Swift社区5 小时前
LeetCode 423 - 从英文中重建数字
算法·leetcode·职场和发展
bbq粉刷匠6 小时前
力扣--两数之和(Java)
java·leetcode
树在风中摇曳6 小时前
LeetCode 1658 | 将 x 减到 0 的最小操作数(C语言滑动窗口解法)
c语言·算法·leetcode
.柒宇.7 小时前
力扣hoT100之找到字符串中所有字母异位词(java版)
java·数据结构·算法·leetcode
YoungHong19928 小时前
面试经典150题[063]:删除链表的倒数第 N 个结点(LeetCode 19)
leetcode·链表·面试
青山的青衫9 小时前
【前后缀】Leetcode hot 100
java·算法·leetcode
啊吧怪不啊吧10 小时前
二分查找算法介绍及使用
数据结构·算法·leetcode