My solution but complex


  • 0
    V
    class Solution {
    public:
        bool isPalindrome(ListNode* head) {
            if( !head || !head->next )
                return true;
        
            /* count the length of the list */
            int len = 1;
            ListNode *move = head;
            while( move->next )
            {
                move = move->next;
                len++;
            }
        
            /* find the mid node */
            ListNode *mid = head;
            for( int i = 0; i < ( len + 1 ) / 2; i++ )
                mid = mid->next;
            
            /* reverse the latter part */
            ListNode *tail = move;
            while( mid != tail )
            {
                move = mid->next;
                mid->next = tail->next;
                tail->next = mid;
                mid = move;
            }
        
            /* compare two lists */
            while( mid )
            {
                if( head->val != mid->val )
                    return false;
                head = head->next;
                mid = mid->next;
            }
            return true;
        }
    };

Log in to reply
 

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