方法一:借助数组保存链表数据,然后回文(时间复杂度On,空间复杂度On)
/**
* 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 {
vector<int> val;
public:
bool isPalindrome(ListNode* head) {
if (!head || !head->next) return true;
ListNode* curr = head;
while (curr) {
val.push_back(curr->val);
curr = curr->next;
}
int n = val.size();
int left = 0, right = n - 1;
while (left < right)
if (val[left++] != val[right--]) return false;
return true;
}
};
方法二:快慢指针+翻转子链表(时间复杂On, 空间复杂度O1)
class Solution {
public:
bool isPalindrome(ListNode* head) {
if (!head || !head->next) return true;
// 快慢指针获得中间节点
ListNode* slow = head, *fast = head;
while (fast->next && fast->next->next) {
slow = slow->next;
fast = fast->next->next;
}
ListNode* subList = slow->next;
slow->next = nullptr;
// 翻转中间节点之后的子链表
ListNode* subReversedList = reverseList(subList);
// 判断是否回文
bool ans = true;
ListNode * List1 = head, *List2 = subReversedList;
while (List1 && List2) {
if (List1->val != List2->val) ans = false;
List1 = List1->next;
List2 = List2->next;
}
// 还原链表
slow->next = reverseList(subReversedList);
return ans;
}
// 翻转链表函数
ListNode* reverseList(ListNode* head) {
ListNode *pre = nullptr, *curr = head;
while (curr) {
ListNode* tempNext = curr->next;
curr->next = pre;
pre = curr;
curr = tempNext;
}
return pre;
}
};