链接:https://leetcode.com/problems/palindrome-linked-list/
思路
- 快慢指针找到中间,划分出长n/2的两部分
- 对比两部分。可以在慢指针迭代时就用vector记录前半部分,然后逆序迭代vector,与后半部分依次比较;也可以在慢指针迭代时反转前半链表,然后两部分直接依次比较。这里使用第一种办法,空间复杂度O(n),但写起来更清晰。
代码
/**
* 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 || !head->next) return true;
// use fast and slow pointers to find the middle,
// and store the first half
vector<int> half;
ListNode *fast = head, *slow = head;
half.push_back(slow->val);
while(true) {
if(!fast->next) { // 奇
slow = slow->next;
half.pop_back();
break;
} else if(!fast->next->next) { // 偶
slow = slow->next;
break;
} else {
fast = fast->next->next;
slow = slow->next;
half.push_back(slow->val);
}
}
// compare the first and the second half
for(int i = half.size() - 1; i >= 0; i--) {
if(slow->val != half[i]) return false;
slow = slow->next;
}
return true;
}
};