文章目录
- 题目描述
- 法一 将值复制到数组中后用双指针法
- 法二 快慢指针
题目描述
法一 将值复制到数组中后用双指针法
class Solution {
public:
bool isPalindrome(ListNode* head) {
vector<int> v;
while(head!=NULL){
v.emplace_back(head->val);
head = head->next;
}
for(int i=0, j=v.size()-1; i<j; i++, j--){
if(v[i]!=v[j]){
return false;
}
}
return true;
}
};
法二 快慢指针
class Solution{
public:
bool isPalindrome(ListNode* head){
if(head == NULL){
return true;
}
ListNode* FirstHalfEnd = fun1(head);
ListNode* SecondHalfStart = fun2(FirstHalfEnd->next);
bool res = true;
ListNode* p1 = head;
ListNode* p2 = SecondHalfStart;
while(res && p2!=NULL){
if(p1->val != p2->val){
res = false;
}
p1 = p1->next;
p2 = p2->next;
}
FirstHalfEnd = fun2(SecondHalfStart)
return res;
}
ListNode* fun1(ListNode* head){
ListNode* fast = head;
ListNode* slow = head;
while(fast->next!=NULL && fast->next->next!=NULL){
fast = fast->next->next;
slow = slow->next;
}
return slow;
}
ListNode* fun2(ListNode* head){
ListNode* prev = NULL;
ListNode* cur = head;
while(cur!=NULL){
ListNode* temp = cur->next;
cur->next = prev;
prev = cur;
cur = temp;
}
return prev;
}
};