20 lines concise and easy understand c++ solution O(n) time, O(1) space


  • 0
    A
    class Solution {
    public:
        bool isPalindrome(ListNode* head) {
            if(!head || !head->next) return true;
            ListNode* fast(head), *slow(head);
            while(fast->next != NULL && fast->next->next != NULL){
                slow = slow->next;
                fast = fast->next->next;
            }
            ListNode* pre = slow->next;
            while(pre->next){
                ListNode* cur = pre->next;
                cout<<cur->val<<endl;
                pre->next = cur->next;
                cur->next = slow->next;
                slow->next = cur;
            }
            slow = slow->next;
            while(slow){
                if(head->val != slow->val) return false;
                head = head->next;
                slow = slow->next;
            }
            return true;
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.