牛客:OR36 链表的回文结构

OR36 链表的回文结构
在这里插入图片描述

/*
struct ListNode {
    int val;
    struct ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};*/
class PalindromeList {
    
    
  public:
    bool chkPalindrome(ListNode* A) 
    {
    
    
        ListNode* shead=(ListNode*)malloc(sizeof(ListNode));
        shead->next=A;
        ListNode* fast=shead;
        ListNode* slow=shead;
        //获得中间节点
        while(fast && fast->next)
        {
    
    
            fast=fast->next->next;
            slow=slow->next;
        }

        ListNode* cur=slow->next;
        ListNode* tmp;
        ListNode* prev=slow;
        slow->next=NULL;

        while(1)
        {
    
    
            tmp=cur->next;
            cur->next=prev;
            if(tmp==NULL) break;
            prev=cur;
            cur=tmp;
        }

        ListNode* head=A;
        ListNode* tail=cur;

        while(tail!=slow)
        {
    
    
            if(head->val!=tail->val) return false;
            tail=tail->next;
            head=head->next;
        }
        return true;
    }
};

详细题解:
超级详细,看了绝对有思路

猜你喜欢

转载自blog.csdn.net/congfen214/article/details/129565746