【LeetCode】剑指 Offer II 027. 回文链表

class Solution {
public:
    int flag=1,midP;
    bool isPalindrome(ListNode* head) {
        ListNode * l1 = head,*l2;
        ListNode * mid = findMid(head);
        l2=mid->next;
        if(!l2)
            return true;
        mid->next = NULL;
        l2=reverseList(l2);

        if(flag)
            ++midP;

        while(midP--){
            if(l1->val!=l2->val){
                return false;
            }
            l1=l1->next;
            l2=l2->next;
        }
        return true;
    }

    ListNode * findMid(ListNode * head)
    {
        ListNode* slow=head;
        ListNode* fast=head;
        while(fast->next&&fast->next->next){
            ++midP;
            slow=slow->next;
            fast=fast->next->next;
            if(fast->next==NULL){
                flag=0;
            }
        }
        return slow;
    }

    ListNode* reverseList(ListNode * head){
        ListNode * pre = NULL,*cur = head, *temp;
        while(cur){
            temp=cur->next;
            cur->next=pre;
            pre=cur;
            cur=temp;
        }
        return pre;
    }
};

思路:找到中间的节点,翻转后半部分,再根据链表元素个数奇偶确定要对比的元素个数。通过对比前后两部分对应位置的val值是否相等,最后可以判断是否是回文。

posted @ 2022-02-23 00:38  Jerry2km1  阅读(40)  评论(0)    收藏  举报