题解 | #链表的回文结构#
链表的回文结构
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* head) {
// write code here
//找到中间结点slow
struct ListNode* fast = head;
struct ListNode* slow = head;
while(fast && fast->next)
{
fast = fast->next->next;
slow = slow->next;
}
//逆置中间结点以后的指针
struct ListNode* cur = slow;
struct ListNode* prev = NULL;
while(cur)
{
struct ListNode* next = cur->next;
cur->next = prev;
prev = cur;
cur = next;
}
struct ListNode* head2 = prev;//head2指向逆置后的第一个几点
//挨个对比
while (head2 && head)
{
if(head2->val != head->val)
{
return false;
}
head = head->next;
head2 = head2->next;
}
return true;
}
};

