/**
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
class Solution {
public:
/**
*
* @param head ListNode类 the head
* @return bool布尔型
*/
ListNode* getMid(ListNode* head) {
if (!head) {
return head;
}
ListNode *slow = head, *fast = head;
while(fast && fast->next) {
slow = slow->next;
fast = fast->next->next;
}
return slow;
}
ListNode* reverse(ListNode* head) {
if (!head) {
return head;
}
ListNode *pre = nullptr, *curr = head;
while(curr) {
ListNode *next = curr->next;
curr->next = pre;
pre = curr;
curr = next;
}
return pre;
}
bool isPail(ListNode* head) {
// reverse mid 之后的链表,开始逐个递归。
ListNode *mid = getMid(head);
ListNode *l1 = head, *l2 = mid->next;
mid->next = nullptr;
l2 = reverse(l2);
while(l1 && l2) {
if (l1->val != l2->val) {
return false;
}
l1 = l1->next;
l2 = l2->next;
}
return true;
// write code here
}
};