https://leetcode.com/problems/palindrome-linked-list/
思路1:遍历一次链表,用一个数组存储链表节点值,然后用双指针法判断数组是否是回文的。需要额外O(n)的空间。
C++
class Solution {
public:
bool isPalindrome(ListNode* head) {
if (!head || !head->next) return true;
vector<int> vec;
while (head) {
vec.push_back(head->val);
head = head->next;
}
for (int i = 0, j = vec.size() - 1; i < j; i++, j--) {
if (vec[i] != vec[j]) return false;
}
return true;
}
};
思路2:如果不使用额外空间的话,就必须修改输入链表了。先找到链表中点,然后将右半部分链表反转,再判断左右两个链表节点值是否相等。
class Solution {
public:
bool isPalindrome(ListNode* head) {
if (!head || !head->next) return true;
// find middle node
ListNode *slow = head, *fast = head->next;
while (fast && fast->next) {
slow = slow->next;
fast = fast->next->next;
}
ListNode *l = head, *r = slow->next;
slow->next = NULL; // cut
// reverse r
r = reverse_list(r);
// is equal
while (l && r) {
if (l->val != r->val) return false;
l = l->next;
r = r->next;
}
return true;
}
ListNode* reverse_list(ListNode* head) {
ListNode *prev = NULL;
while (head) {
ListNode *next = head->next;
head->next = prev;
prev = head;
head = next;
}
return prev;
}
};