Faster C++ solution, O(n) time and O(1) memory


  • 0
    M

    class Solution {
    public:
    bool isPalindrome(ListNode* head) {
    if(head == NULL || head->next == NULL) return true;
    ListNode *slow = head, *slowNext = head->next, *fast = head->next->next;

        while(fast)
        {
            slow->next = slowNext->next;
            slowNext->next = head;
            head = slowNext;
            slowNext = slow->next;
            if(fast->next)
            {
                fast = fast->next->next;
            }
            else
            {
                break;
            }
        }
        if(fast) //odd list
        {
           head = head->next;    
        }
        while(slowNext)
        {
            if(head->val != slowNext->val) return false;
            head = head->next;
            slowNext = slowNext->next;
        }
        return true;
    }
    

    };


Log in to reply
 

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