题目描述:
请判断一个链表是否为回文链表。
示例 1:
输入: 1->2
输出: false
示例 2:
输入: 1->2->2->1
输出: true
思路:
1、快慢指针找到中间位置
2、反转后半段链表(参考:https://blog.csdn.net/xu491361421xiao/article/details/81385435)
3、依次判断是否是回文链表
代码如下:
class Solution {
public:
bool isPalindrome(ListNode* head) {
ListNode* slow=head,*fast=head,*newh=NULL;
while(fast){//找到链表的中点
slow=slow->next;
fast=fast->next?fast->next->next:fast->next;
}
while(slow){//反转链表
ListNode* tmp=slow->next;
slow->next=newh;
newh=slow;
slow=tmp;
}
while(head&&newh){
if(head->val!=newh->val){
return false;
}
head=head->next;
newh=newh->next;
}
return true;
}
};