找到中点reverse后半部,跟前半部比对即可,比如[1,2,1]拆成[1]和[2,1],比较[1]跟[1,2]即可
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
|
class Solution { public: bool isPalindrome(ListNode* head) { if (!head || !head->next) return true; ListNode dummy_head(0), *slow = &dummy_head, *fast = head; // fast从head或者dummy_head开始都行 dummy_head.next = head; while (fast && fast->next) { slow = slow->next; fast = fast->next->next; } fast = slow->next; slow->next = nullptr; fast = reverse(fast); while (head && head->val == fast->val) { head = head->next; fast = fast->next; } return !head; }
ListNode *reverse(ListNode *head) { ListNode *prev = nullptr, *curr = head; while (curr) { auto succ = curr->next; curr->next = prev; prev = curr; curr = succ; } return prev; } };
|
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
|
class Solution { public: bool isPalindrome(ListNode* head) { if (!head || !head->next) return true; ListNode *prev = nullptr, *slow = head, *fast = head; while (fast && fast->next) { prev = slow; slow = slow->next; fast = fast->next->next; } fast = fast ? slow->next : slow; auto l2 = reverse(fast); prev->next = nullptr; while (head && l2 && head->val == l2->val) { head = head->next; l2 = l2->next; } return !head; }
ListNode *reverse(ListNode *head) { ListNode *prev = nullptr, *curr = head; while (curr) { auto succ = curr->next; curr->next = prev; prev = curr; curr = succ; } return prev; } };
|
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
|
class Solution { public: bool isPalindrome(ListNode* head) { if (!head || !head->next) return true; ListNode *prev = nullptr, *slow = head, *fast = head; while (fast && fast->next) { prev = slow; slow = slow->next; fast = fast->next->next; } fast = fast ? slow->next : slow; auto l2 = reverse(fast); prev->next = nullptr; while (head && l2 && head->val == l2->val) { head = head->next; l2 = l2->next; } return !head; }
ListNode *reverse(ListNode *head) { if (!head || !head->next) return head; auto res = reverse(head->next); head->next->next = head; head->next = nullptr; return res; } };
|
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
|
class Solution { public: bool isPalindrome(ListNode* head) { if (!head || !head->next) return true; auto slow = head, fast = head; while (fast->next && fast->next->next) { slow = slow->next; fast = fast->next->next; } fast = slow->next; auto l2 = reverse(fast); slow->next = nullptr; if (!fast->next) { fast->next = slow; } while (head && l2 && head->val == l2->val) { head = head->next; l2 = l2->next; } return !head; }
ListNode *reverse(ListNode *head) { if (!head || !head->next) return head; auto res = reverse(head->next); head->next->next = head; head->next = nullptr; return res; } };
|