My C Solution,O(N) time,O(1)space


  • 0
    D

    '''
    bool isPalindrome(struct ListNode* head) {
    struct ListNode* mid_left;
    struct ListNode* mid_right;
    struct ListNode* temp_right;
    struct ListNode* temp;
    int flag = 0;

    if(head == NULL || head->next == NULL)
    return true;
    
    mid_left = head;
    mid_right = head->next;
    mid_left ->next = NULL;
    temp_right = mid_right;
    
    while(temp_right->next != NULL && temp_right != NULL)
    {
        if(temp_right->next->next == NULL)
        {
            flag =1;
            temp_right = temp_right->next;
        }
        else
        temp_right = temp_right->next->next;
        temp = mid_right->next;
        mid_right->next = mid_left;
        mid_left = mid_right;
        mid_right = temp;
    }
    if(flag == 1)
    {
        mid_left = mid_left->next;
    }
    
    while(mid_left!=NULL)
    {
        if(mid_left->val != mid_right->val)
        return false;
        mid_left = mid_left->next;
        mid_right = mid_right->next;
    }
    return true;
    

    }


Log in to reply
 

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