解决这道题的方法有三种:
- 遍历链表得到所有值的数组,用双指针判断【时间复杂度 O ( N ) O(N) O(N) 空间复杂度 O ( N ) O(N) O(N)】
- 利用递归判断【时间复杂度 O ( N ) O(N) O(N) 空间复杂度 O ( N ) O(N) O(N)】
- 反转链表判断【时间复杂度 O ( N ) O(N) O(N) 空间复杂度 O ( 1 ) O(1) O(1)】
附上代码:
递归
class Solution {
ListNode* comp;
public:
bool recurr(ListNode* head){
if(!head) return true;
bool flag = true;
if(head->next) flag = recurr(head->next);
if(head->val != comp->val) flag = false;
comp = comp->next;
return flag;
}
bool isPalindrome(ListNode* head) {
comp = head;
return recurr(head);
}
};
反转链表
class Solution {
ListNode* comp;
public:
ListNode* reverseList(ListNode* h){
ListNode* curr = h;
ListNode* prev = nullptr;
while(curr){
ListNode* t = curr->next;
curr->next = prev;
prev = curr;
curr = t;
}
return prev;
}
bool isPalindrome(ListNode* head) {
int n = 0;
ListNode* temp = head;
while(temp){temp = temp->next; n++;}
temp = head;
//找到分割点
for(int i=1; i<n/2; i++) temp = temp->next;
ListNode* h1 = head;
//构建
ListNode* h2 = reverseList(temp->next);
ListNode* h3 = h2;
if(temp && temp->next)temp->next = nullptr;
//回文串判断
bool out = true;
while(h1 && h2){
if(h1->val != h2->val) out = false;
h1 = h1->next;
h2 = h2->next;
}
//还原链表
temp->next = reverseList(h3);
return out;
}
};