先找到中间节点,然后再比对链表的前半段和后半段。有2种方法
第一种方法:用栈保存前半段
bool isPalindrome(ListNode* head) {
if(head==nullptr)
return true;
ListNode* fast=head;
ListNode* slow=head;
stack<int> stk;
//找中间节点,并存储前半段到栈
while(fast->next!=nullptr && fast->next->next!=nullptr){
fast=fast->next->next;
stk.push(slow->val);
slow=slow->next;
}
if(fast->next!=nullptr){
stk.push(slow->val);
slow=slow->next;
}
else{
slow=low->next;
}
//比较
while(!stk.empty()){
if(stk.top()==slow->val){
stk.pop();
slow=slow->next;
}
else
break;
}
return stk.empty();
}
第二种方法:反转后半段
bool isPalindrome(ListNode* head) {
ListNode* fast=head;
ListNode* slow=head;
//找中间节点
while(fast){
fast=fast->next?fast->next->next:fast->next;
slow=slow->next;
}
//反转链表
ListNode* pre=nullptr;
while(slow){
ListNode* pnext=slow->next;
slow->next=pre;
pre=slow;
slow=pnext;
}
//比较
while(pre && head){
if(head->val!=pre->val){
return false;
}
pre=pre->next;
head=head->next;
}
return true;
}