/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) : val(x), next(nullptr) {}
* };
*/
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param head ListNode类 the head
* @return bool布尔型
*/
bool isPail(ListNode* head) {
// write code here
auto temp=head;
int count=0;
while(temp){
count++;
temp=temp->next;
}
int mid=count/2;
if(mid==0) return true;
temp=head;
ListNode* midPtr;
//寻找中间位置
while(mid--){
midPtr=temp;
temp=temp->next;
}
//断开链表
temp=midPtr->next;
midPtr->next=nullptr;
//将链表后半段反转
auto post=reverseList(temp);
printList(post);
temp=head;
//判断两串是否相等
while(temp&&post){
if(temp->val !=post->val) return false;
temp=temp->next;
post=post->next;
}
return true;
}
//反转链表
ListNode* reverseList(ListNode* head){
ListNode* prev=nullptr;
while(head != nullptr){
//断开后序
ListNode* next = head->next;
//指向前序
head->next = prev;
prev = head;
head = next;
}
return prev;
}
void printList(ListNode* head){
while(head){
std::cout<<head->val<<" ";
head=head->next;
}
std::cout<<endl;
}
};