力扣细节题:回文链表

注意中间节点的寻找

复制代码
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;
}
相关推荐
无敌最俊朗@2 小时前
数组-力扣hot56-合并区间
数据结构·算法·leetcode
码农多耕地呗3 小时前
力扣94.二叉树的中序遍历(递归and迭代法)(java)
数据结构·算法·leetcode
微笑尅乐3 小时前
BFS 与 DFS——力扣102.二叉树的层序遍历
leetcode·深度优先·宽度优先
白云千载尽5 小时前
leetcode 912.排序数组
算法·leetcode·职场和发展
代码充电宝5 小时前
LeetCode 算法题【简单】290. 单词规律
java·算法·leetcode·职场和发展·哈希表
And_Ii6 小时前
LeetCode 3397. 执行操作后不同元素的最大数量
数据结构·算法·leetcode
额呃呃6 小时前
leetCode第33题
数据结构·算法·leetcode
dragoooon347 小时前
[优选算法专题四.前缀和——NO.27 寻找数组的中心下标]
数据结构·算法·leetcode
1白天的黑夜111 小时前
递归-24.两两交换链表中的节点-力扣(LeetCode)
数据结构·c++·leetcode·链表·递归
1白天的黑夜112 小时前
递归-206.反转链表-力扣(LeetCode)
数据结构·c++·leetcode·链表·递归