原题链接
Note:
把后面一半翻转一下,然后判断 LeetCode里 最后得把链表复原回去 要不然评测有问题
half = n / 2 翻转的数量是 half - 1 找到起始的翻转点是 n - half 要判断的数量是 half 画图找出来这几个数之后就可以敲代码了
代码如下:
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 l = head, r = a;
bool succ = true;
for(int i = 0; i < half; i ++){
if(l -> val != r -> val){
succ = false;
break;
}
l = l -> next;
r = r -> 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 succ;
}
};
|