题解 | #链表的回文结构#

链表的回文结构

https://www.nowcoder.com/practice/d281619e4b3e4a60a2cc66ea32855bfa

class PalindromeList {
public:
    ListNode* reverse(ListNode *A){
        if(A->next == nullptr){
            return A;
        }
        ListNode * fastP = A -> next;
        ListNode * slowP = A;
        while(fastP->next != nullptr){
            ListNode *fastNext = fastP->next;
            fastP->next =slowP;
            slowP = fastP;
            fastP = fastNext;
        }
        A ->next =nullptr;
        return fastP;
    }
    bool chkPalindrome(ListNode* A) {
        // write code here
        if(A->next == nullptr){
            return false;
        }
        if(A->next->next ==nullptr ){
            if(A->val == A->next->val){
                return true;
            }
            return false;
        }
        ListNode * begin = A;
        ListNode * fastP = A;
        ListNode * slowP = A;
        while(fastP->next!= nullptr && fastP->next->next != nullptr  ){
            fastP = fastP->next->next;
            slowP = slowP->next;
        }
        
            slowP = slowP -> next; //奇数 偶数都需要处理
        
        ListNode* reverseList = reverse(slowP);
        while(reverseList != nullptr && begin !=nullptr){
            if(reverseList -> val != begin ->val){
                return false;
            }
            reverseList = reverseList->next;
            begin =begin->next;
        }
        return true;
    }
};

全部评论

相关推荐

点赞 评论 收藏
分享
06-02 15:53
阳光学院 Java
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
07-24 13:35
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务