【LeetCode 234_链表】Palindrome Linked List
1 ListNode* ReverseList(ListNode *p) { 2 if (p == NULL || p->next == NULL) 3 return p; 4 5 ListNode *pre = NULL; 6 ListNode *next = p->next; 7 while (p) { 8 p->next = pre; 9 pre = p; 10 p = next; 11 next = p ? p->next : NULL; 12 } 13 return pre; 14 } 15 16 bool isPalindrome(ListNode* head) { 17 if (head == NULL || head->next == NULL) 18 return true; 19 ListNode *slow = head, *fast = head; 20 while (fast->next && fast->next->next) { 21 slow = slow->next; 22 fast = fast->next->next; 23 } 24 slow->next = ReverseList(slow->next); 25 slow = slow->next; 26 27 while (slow) { 28 if (slow->val != head->val) 29 return false; 30 slow = slow->next; 31 head = head->next; 32 } 33 return true; 34 }