OR36 链表的回文结构

描述

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

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

测试样例:

1->2->2->1
返回:true

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

 反转链表和快慢指针

/*
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;
    }
};

上一篇:使用Python实现主成分分析(PCA)


下一篇:大模型学习_zhipu_ai调用函数-demo