1、先找到链表的中点位置,用快慢指针实现。
while(fast!=nullptr&&fast->next!=nullptr){
slow=slow->next;
fast=fast->next->next;
}//快慢指针
fast=slow->next;
slow->next=nullptr;
2、将中点的右侧进行反转。
while(fast!=nullptr){
nex=fast->next;
fast->next=slow;
slow=fast;
fast=nex;
}//右边反转,整个循环下来slow在开头
fast=slow;
3、然后两端的数一一对比。
while(head!=nullptr&&fast!=nullptr){
if(head->val!=fast->val){
return false;
}
head=head->next;
fast=fast->next;
}
return true;
方法二:数组
vector<int> nums;
ListNode* cur = head;
while(cur){
nums.push_back(cur->val);
cur = cur->next;
}
for(int i = 0, j = nums.size() - 1; i<j; i++, j--){
if(nums[i] != nums[j]) return false;
}
return true;
方法三:栈
stack<int> s;
for(auto p=head;p;p=p->next) s.push(p->val);
for(auto q=head;q;q=q->next){
auto xx=s.top();
s.pop();
if(q->val!=xx){
return 0;
}
}
return 1;