Steward
分享是一種喜悅、更是一種幸福
程式語言 - LeetCode - C++ - 234. Palindrome Linked List
題目:

方法:
1. 找中點(快慢指標) 2. 反轉後半段linked list 3. 比較前半 vs 後半
解答:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
bool isPalindrome(ListNode* head) {
ListNode *fast = head;
ListNode *slow = head;
while (fast && fast->next) {
slow = slow->next;
fast = fast->next->next;
}
ListNode* pre = nullptr;
while (slow) {
ListNode *next = slow->next;
slow->next = pre;
pre = slow;
slow = next;
}
while (pre) {
if (pre->val != head->val) {
return false;
}
head = head->next;
pre = pre->next;
}
return true;
}
};