leetcode 234. Palindrome Linked List
快慢指针找到中点,反转后半段,比较。
其实慢指针走的时候就可以开始反转。
bool isPalindrome(ListNode* head) { if (head == NULL || head->next == NULL) return true; if (head->next->next == NULL) return head->val == head->next->val; ListNode* fast = head; ListNode* slow = head; while (fast) { fast = fast->next; if (!fast) { slow = slow->next; break; } fast = fast->next; slow = slow->next; } slow = invertList(slow); while (slow) { if (head->val != slow->val) return false; head = head->next; slow = slow->next; } return true; } ListNode* invertList(ListNode* root) { ListNode* ret = NULL; while (root) { ListNode* temp = root->next; root->next = ret; ret = root; root = temp; } return ret; }
【本文章出自博客园willaty,转载请注明作者出处,误差欢迎指出~】