Time Limit Exceeded for Palindrome linked list


  • 0
    L

    Could anyone help me with this? I think it is OK.

    class Solution {
    public:
        bool isPalindrome(ListNode* head) {
            if(!head || !head->next)
                return true;
            ListNode* slow = head, *fast = head;
            while(fast && fast->next){
                slow = slow->next;
                fast = fast->next->next;
            }
    
            //reverse from head to mid
            ListNode* p = head->next, *q;
            while(p != slow){
                q = p->next;
                p->next = head;
                head = p;
                p = q;
            }
            if(fast)//odd number
                p = p->next;
            while(p){
                if(p->val != head->val){
                    return false;
                }
                p = p->next;
                head = head->next;
            }
            return true;
        }
    };
    

Log in to reply
 

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