OR36 链表的回文结构

描述

对于一个链表,请设计一个时间复杂度为O(n),额外空间复杂度为O(1)的算法,判断其是否为回文结构。

给定一个链表的头指针A,请返回一个bool值,代表其是否为回文结构。保证链表长度小于等于900。

测试样例:

复制代码
1->2->2->1
复制代码
返回:true

思路:找到链表的中间节点(偶数个的话取右边那个)然后把从中间节点开始反转链表然后在用反转后的链表和反转的前半部分的链表比

反转链表和快慢指针

cpp 复制代码
/*
struct ListNode {
    int val;
    struct ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};*/
typedef struct ListNode LN;

class PalindromeList {
public:
    LN* reverList(LN* head)
    {
        if(head==NULL)
        {
            return head;
        }
        LN* n1,*n2,*n3;
        n1=NULL;
        n2=head;
        n3=head->next;
        while(n2)
        {
            n2->next=n1;
            n1=n2;
            n2=n3;
            if(n3)
            {
                n3=n3->next;
            }
        }
        return n1;
    }
    LN* midNode(LN* head)
    {
        LN* fast,* slow;
        fast=slow=head;
        while(fast && fast->next)
        {
            slow=slow->next;
            fast=fast->next->next;
        }
        return slow;
    }
    bool chkPalindrome(ListNode* A) {
        // write code here
        LN* midnode=midNode(A);
        LN* remid=reverList(midnode);
        while(A && remid)
        {
            if(A->val !=remid->val)
            {
                return false;
            }
            A=A->next;
            remid=remid->next;
        }
        return true;
    }
};
相关推荐
变量未定义~26 分钟前
单调栈、单调队列(模板)、子矩阵(模板)
数据结构·算法·蓝桥杯
不会就选b36 分钟前
算法日常・每日刷题--<快速排序>2
数据结构·算法
shx_wei1 小时前
从函数调用到进程替换:使用 execl、CMake 与 PowerShell 构建一个多可执行程序
linux·c语言·windows·c
kyle~2 小时前
Schema---数据结构的形式化规则描述
数据结构·windows·microsoft
李小小钦3 小时前
D. Storming Arasaka(Codeforces 2238)
c语言·开发语言·数据结构·c++·算法
先吃饱再说3 小时前
一篇吃透树的遍历:递归与迭代的完整拆解
数据结构·算法
gugucoding15 小时前
21. 【C语言】打包不同类型:结构体
c语言·开发语言
gugucoding16 小时前
31. 【C语言】堆栈与队列的实现
c语言·开发语言·数据结构·链表
ChaoZiLL17 小时前
我的数据结构3——链表(link list)
数据结构·链表
王老师青少年编程19 小时前
2026年6月GESP真题及题解(C++七级):消消乐
数据结构·c++·算法·真题·gesp·2026年6月