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) {
        if(head==nullptr||head->next==nullptr)
            return true;
        ListNode* slow=head,*fast=head;
        while(fast->next!=nullptr&&fast->next->next!=nullptr)
        {
            slow=slow->next;
            fast=fast->next->next;
        }
        
        slow->next=reverseList(slow->next);
        slow=slow->next;
        while(slow!=nullptr)
        {
            if(head->val!=slow->val)
                return false;
            head=head->next;
            slow=slow->next;
        }
        return true;
        
    }
    
    ListNode* reverseList(ListNode* head)
    {
        ListNode* rail=nullptr,*next=nullptr;
        while(head!=nullptr)
        {
            next=head->next;
            head->next=rail;
            rail=head;
            head=next;
        }
        return rail;
    }
   
};

思路

先将链表后半部分逆转,比如[abccba],逆转之后为[abcabc],然后从索引0和链表中间开始同时遍历判断是否相等。

https://github.com/li-zheng-hao
原文地址:https://www.cnblogs.com/lizhenghao126/p/11053631.html