24.判断回文链表

1.题目描述

2.思路

前面两题都是为了这一题做准备的,思路就是双指针先找到中间节点,然后翻转后半段,然后依次对比即可

3.代码

cpp 复制代码
bool isPalindrome(struct ListNode* head) {
   if (head == NULL || head->next == NULL) {
        return true;
    }
    struct ListNode* p1 = head;
    int len = 0;
    while(p1!=NULL){
        len++;
        p1 = p1->next;
    }

    int mid = len/2;//找到后半段的首个节点
    p1 = head;//继续用p1
    while(mid>0){
        p1 = p1->next;
        mid--;
    }//此时p1指向后半段
    //开始反转后半段
    struct ListNode* pre = NULL;
    struct ListNode* cur = p1;
    struct ListNode* nextp=NULL;
    while(cur!=NULL){
        nextp = cur->next;
        cur->next = pre;
        pre = cur;
        cur=nextp;
    }
    //此时cur就是后半段反转的头节点
    //开始判断回文
    while(pre!=NULL){
        if(head->val != pre->val){
            return false;
        }
        pre = pre->next;
        head = head->next;
    }
    return true;
}
相关推荐
皮皮哎哟1 小时前
数据结构:嵌入式常用排序与查找算法精讲
数据结构·算法·排序算法·二分查找·快速排序
堕2741 小时前
java数据结构当中的《排序》(一 )
java·数据结构·排序算法
2302_813806222 小时前
【嵌入式修炼:数据结构篇】——数据结构总结
数据结构
Wei&Yan2 小时前
数据结构——顺序表(静/动态代码实现)
数据结构·c++·算法·visual studio code
long3163 小时前
Aho-Corasick 模式搜索算法
java·数据结构·spring boot·后端·算法·排序算法
张张努力变强5 小时前
C++ STL string 类:常用接口 + auto + 范围 for全攻略,字符串操作效率拉满
开发语言·数据结构·c++·算法·stl
wWYy.5 小时前
数组快排 链表归并
数据结构·链表
李斯啦果6 小时前
【PTA】L1-019 谁先倒
数据结构·算法
Mr Xu_21 小时前
告别硬编码:前端项目中配置驱动的实战优化指南
前端·javascript·数据结构
czxyvX21 小时前
017-AVL树(C++实现)
开发语言·数据结构·c++