力扣:回文链表

找到中间位置节点,一个指针走两步,一个指针走一步即可。将后面的链表反转。两个链表对比即可。

class Solution {
public:
    bool isPalindrome(ListNode* head) {
        if(!head) return true;
        ListNode* fastnode = head;
        ListNode* slownode = head;
        while( fastnode->next && fastnode->next->next){
            fastnode = fastnode->next->next;
            slownode = slownode->next;
        }
        slownode = reverse(slownode->next);
        fastnode = head;
        while(slownode){
            if(slownode->val != fastnode->val) return false;
            slownode = slownode->next;
            fastnode = fastnode->next;
        }
        return true;
    }
    ListNode* reverse(ListNode* head){
        ListNode* pre = nullptr;
        while(head){
            ListNode* down = head->next;
            head->next = pre;
            pre = head;
            head = down;
        }
        return pre;
    }
};  




你可能感兴趣的:(蓝桥,leetcode,算法,深度优先)