题解 | #链表的回文结构#中间节点的查找+链表逆转
链表的回文结构
https://www.nowcoder.com/practice/d281619e4b3e4a60a2cc66ea32855bfa
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};*/
class PalindromeList {
public:
bool chkPalindrome(ListNode* phead) {
if(!phead || !(phead->next))
{
return true;
}
ListNode* fast, * slow;//用于查找中间节点
ListNode* n1, * n2, * n3;//用于逆转前半部分的链表
fast = slow = phead;
n1 = nullptr;
n2 = phead;
n3 = n2->next;
//寻找中间节点的同时逆转前半部分的链表
//每一次循环结束n2与slow指向同一个节点
while(fast && fast->next)
{
//迭代查找中间节点
slow = slow->next;
fast = fast->next->next;
//扭转指针指向
n2->next = n1;
//迭代
n1 = n2;
n2 = n3;
n3 = n3->next;
}
//判断是否为回文串
while(slow)
{
if(fast)
{
slow = slow->next;
fast = fast->next;
}
if(n1->val != slow->val)
{
return false;
}
n1 = n1->next;
slow = slow->next;
}
return true;
}
};
