细节实现题,在纸上画了一会才AC
/**
* 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;
ListNode* slow = head;
ListNode* fast = head;
ListNode* cnt = new ListNode(-1);
ListNode* h = cnt;
cnt->next = head;
int len = 0;
while(cnt->next){
++len;
cnt = cnt->next;
}
if(len == 1) return true;
int half = (len + 1) >> 1;
while(half){
h = h->next;
--half;
}
h = reverse(h);
h = h->next;
while(h){
if(h->val != head->val)
return false;
else{
h = h->next;
head = head->next;
}
}
return true;
}
ListNode* reverse(ListNode* h){
ListNode* pre = h->next;
ListNode* cur = pre->next;
ListNode* next = nullptr;
while(cur){
next = cur->next;
cur->next = h->next;
h->next = cur;
pre->next = next;
cur = next;
}
return h;
}
};