234. Palindrome Linked List
Given the head of a singly linked list, return true if it is a palindrome.
Follow up: Could you do it in O(n) time and O(1) space?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
|
class Solution { public: bool isPalindrome(ListNode* head) { if(!head->next) return true; if(!head->next->next) return head->next->val == head->val;
ListNode *mid = head, *tail = head, *prev = NULL, *nxt; while(tail->next and tail->next->next) { tail = tail->next->next; nxt = mid->next; mid->next = prev; prev = mid; mid = nxt; } if(!tail->next) mid = mid->next; else { nxt = mid->next; mid->next = prev; prev = mid; mid = nxt; } while(mid != NULL and prev != NULL) { if(mid->val != prev->val) return false; mid = mid->next; prev = prev->next; } return !mid and !prev; } };
|