分块写逻辑更清楚一点
思路:快慢指针查找中点,然后翻转链表206题,然后比较是否相等
时间复杂度:3/2 O(n) ,空间复杂度O(1)
class Solution {
public:
bool isPalindrome(ListNode* head) {
if (head == nullptr) {
return true;
}
// 找到前半部分链表的尾节点并反转后半部分链表
ListNode* firstHalfEnd = endOfFirstHalf(head);
ListNode* secondHalfStart = reverseList(firstHalfEnd->next);
// 判断是否回文
ListNode* p1 = head;
ListNode* p2 = secondHalfStart;
bool result = true;
while (result && p2 != nullptr) {
if (p1->val != p2->val) {
result = false;
}
p1 = p1->next;
p2 = p2->next;
}
// 还原链表并返回结果
firstHalfEnd->next = reverseList(secondHalfStart);
return result;
}
ListNode* reverseList(ListNode* head) {
ListNode* prev = nullptr;
ListNode* curr = head;
while (curr != nullptr) {
ListNode* nextTemp = curr->next;
curr->next = prev;
prev = curr;
curr = nextTemp;
}
return prev;
}
ListNode* endOfFirstHalf(ListNode* head) {
ListNode* fast = head;
ListNode* slow = head;
while (fast->next != nullptr && fast->next->next != nullptr) {
fast = fast->next->next;
slow = slow->next;
}
return slow;
}
};
class Solution {
public:
bool isPalindrome(ListNode* head) {
ListNode*fast=head;
ListNode*slow=head;
while(fast!=nullptr&&fast->next!=nullptr){
fast=fast->next->next;
slow=slow->next;
}
ListNode*pre=nullptr;
ListNode*cur=slow;
while(cur!=nullptr){
ListNode*temp=cur->next;
cur->next=pre;
pre=cur;
cur=temp;
}
while(pre!=nullptr){
if(pre->val!=head->val)
return false;
pre=pre->next;
head=head->next;
}
return true;
}
};
class Solution {
public:
bool isPalindrome(ListNode* head) {
vector<ListNode*>vec;
while(head!=nullptr){
vec.emplace_back(head);
head=head->next;
}
for(int i=0,j=vec.size()-1;i<j;i++,j--){
if(vec[i]->val!=vec[j]->val)
return false;
}
return true;
}
};
递归
相当于在每次递归中判断当前递归函数中和temp是否相等,相等返回true递归到上一次curNode中,不相等就false
class Solution {
public:
ListNode*temp;
bool myPalind(ListNode*curNode){
if(curNode!=nullptr){
if(!myPalind(curNode->next))
return false;
if(curNode->val!=temp->val)
return false;
temp=temp->next;
}
return true;
}
bool isPalindrome(ListNode* head) {
temp=head;
return myPalind(head);
}
};