/** * 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) return true;
        if(!head->next) return true;
        ListNode* fast = head, *slow = head;
        bool res = true;
        //快慢指针 找到中点
        while(fast&&fast->next){
            slow = slow->next;
            fast =fast->next->next;
        }
        ListNode* cur = slow->next;
        ListNode* pre = slow;
        //反转中点后面的链表 中点的next连接null
        while(cur) {
            ListNode* temp = cur->next;
            cur->next = pre;
            pre = cur;
            cur = temp;
        }
        slow->next = NULL;
        ListNode* last = pre;
        cur = head;
        //两头开始比对 直到遇到空停止
        while(pre&&cur) {
            if(pre->val!=cur->val) {
                res = false;
                break;
            }
            pre = pre->next;
            cur = cur->next;
        }
        //将中点之后的结点反转还原
        cur = last->next;
        pre = last;
        while(cur) {
            ListNode* temp = cur->next;
            cur->next = pre;
            pre = cur;
            cur = temp;
        }
        last->next = NULL;
        //确认还原正确
        while(head) {
            cout << head->val << endl;
            head = head->next;
        }
        return  res;
        
    }
};

分析:

判断一个单链表是不是回文串 :
链表的题目基本就是优化时间:如果采用数组存储的方式需要o(n)的额外的空间。
所以这个涉及的是链表的处理操作。先是但快慢指针找中点,就地反转单链表,再还原。

小细节:

while(fast&&fast->next){
   slow = slow->next;
   fast = fast->next->next;
}

判断的条件,这样统一奇数和偶数的情况:
如果是奇数慢指针落在正中间,如果是偶数慢指针落在中间两个当中的后一个。