力扣细节题:回文链表

注意中间节点的寻找

复制代码
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;
}
相关推荐
郝学胜-神的一滴8 小时前
Effective STL 条款 07:指针容器销毁前先删除
开发语言·c++·vscode·leetcode·rpc·visual studio
CoderYanger8 小时前
A.每日一题:2243. 计算字符串的数字和
java·开发语言·程序人生·leetcode·面试·蓝桥杯·学习方法
Navigator_Z12 小时前
LeetCode //C - 1323. Maximum 69 Number
c语言·算法·leetcode
Pniubi2 天前
力扣2 . 两数相加
算法·leetcode·职场和发展
文丑颜不良啊2 天前
LeetCode3401~3420题目解析
java·leetcode
文丑颜不良啊2 天前
LeetCode3421~3440题目解析
java·leetcode
LK_073 天前
【力扣】142. 环形链表 II |Python
python·leetcode·链表
Pniubi3 天前
力扣21合并两个有序链表
算法·leetcode·职场和发展
文丑颜不良啊3 天前
LeetCode3341~3360题目解析
java·leetcode
Rain的Java大神之路3 天前
把数组本身变成哈希表:原地哈希搞定 LeetCode 41「缺失的第一个正数」
java·后端·leetcode