力扣[LeetCode].234. 回文链表

在这里插入图片描述

第一步将后一半翻转
第二步判断是否对称
第三步将后一半翻转回来
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
    
    
public:
    bool isPalindrome(ListNode* head) {
    
    
        int n=0;
        for(auto p=head;p;p=p->next) n++;
        if(n<=1) return true;
        int half=n/2;
        auto a=head;
        for(int i=0;i<n-half;i++) a=a->next;
        auto b=a->next;
        for(int i=0;i<half-1;i++){
    
    
            auto c=b->next;
            b->next=a;
            a=b,b=c;        
        }
    auto p=head,q=a;
    bool success=true;
    for(int i=0;i<half;i++){
    
    
        if(p->val != q->val){
    
    
            success=false;
            break;
        }
        p=p->next;
        q=q->next;
    }
    auto tail=a;
    b=a->next;
    //将链表恢复原状
    for(int i=0;i<half-1;i++){
    
    
        auto c=b->next;
        b->next=a;
        a=b,b=c;
    }
    tail->next=NULL;
    return success;
    }
};

猜你喜欢

转载自blog.csdn.net/weixin_45488131/article/details/108902100
今日推荐