思路:先查找中间节点,然后将后半段逆置 结束条件:有一个为空就结束 查找中间节点:
struct ListNode* middleNode(struct ListNode* head) {
struct ListNode* slow = head, * fast = head;
while (fast && fast->next) {
slow = slow->next;
fast = fast->next->next;
}
return slow;
}
中间节点以及中间节点后的代码逆置:
struct ListNode* reverseList(struct ListNode* head) {
struct ListNode* cur = head;
struct ListNode* newhead = NULL;
while (cur) {
struct ListNode* next = cur->next;
//头插
cur->next = newhead;
newhead = cur;
cur = next;
}
return newhead;
}
判断是否为回文结构:
struct ListNode* mid = middleNode(A);
struct ListNode* rmid = reverseList(mid);
while(rmid && A)
{
if(rmid->val != A->val)
return false;
rmid = rmid->next;
A = A->next;
}
return true;
}