题目
力扣
思路一 存储+双指针
先用vector吧链表中的数据存下来,再用双指针判断是否是回文链表。
代码一
class Solution {
public:
bool isPalindrome(ListNode* head) {
vector<int> v;
while(head){
v.emplace_back(head->val);
head=head->next;
}
int i=0,j=v.size()-1;
while(i<j){
if(v[i++]!=v[j--])
return false;
}
return true;
}
};
思路二 寻找链表中点+链表逆序
先找到链表的中点,再把后面部分逆序,然后比较每个结点,判断是否是回文。
代码二
class Solution {
public:
bool isPalindrome(ListNode* head) {
ListNode* mid=middleNode(head);
ListNode* l2=reverseList(mid);
while(head && l2){
if(head->val!=l2->val)
return false;
head=head->next;
l2=l2->next;
}
return true;
}
ListNode* middleNode(ListNode* head){
ListNode *slow=head,*fast=head;
while(fast && fast->next){
slow = slow->next;
fast = fast->next->next;
}
return slow;
}
ListNode* reverseList(ListNode* head){
ListNode *pre=nullptr,*cur=head;
while(cur){
ListNode *t=cur->next;
cur->next=pre;
pre=cur;
cur=t;
}
return pre;
}
};
思路三 递归
双指针,使用一个指针从前往后遍历,另一个指针从后往前遍历(通过迭代实现),遍历过程中判断链表是否是回文。
代码三
class Solution {
public:
ListNode* frontNode;
bool check(ListNode* curNode){
if(curNode){
if(!check(curNode->next))
return false;
if(frontNode->val != curNode->val)
return false;
frontNode=frontNode->next;
}
return true;
}
bool isPalindrome(ListNode* head) {
frontNode=head;
return check(head);
}
};