C++ time O(n) space O(1) but it says that TLE


  • 0
    Y

    I have test my code on my computer.It goes well. But I dont know why it's TLE here.

    class Solution {
    
    
    public:
        bool isPalindrome(ListNode* head) {
            if (head==NULL)
            {
                return false;
            }
            int node_num=1;
            ListNode * temp=head;
            while (temp->next!=NULL)
            {
                temp=temp->next;
                node_num++;
            }
            if (node_num==1)
            {
                return true;
            }
            ListNode* cutFromMid=splitList(head,node_num/2);
            cutFromMid=reverseList(cutFromMid,temp);
    		int count=1;
            while (count<=(node_num/2))
            {
                if (cutFromMid->val!=head->val)
                {
                    return false;
                }else{
                    cutFromMid=cutFromMid->next;
                    head=head->next;
                }
    			count++;
            }
            return true;
        }
        ListNode * reverseList(ListNode*begin,ListNode *end)
        {
            ListNode*former=NULL;
            ListNode*temp=begin;
            if (begin==end)
            {
                return begin;
            }
            ListNode*next_temp=temp->next;
            while (next_temp!=end)
            {
                temp->next=former;
                former=temp;
                temp=next_temp;
                next_temp=next_temp->next;
            }
            end->next=temp;
            return end;
        }
        ListNode * splitList(ListNode* head,int length)
        {
            ListNode* temp=head;
            int count=1;
            while (count<=length)
            {
                temp=temp->next;
                count++;
            }
            return temp;
        }
    };

  • 0
    Z

    Have you tried make the tail of the first half of the linked list link to NULL?


  • 0
    Y

    No,but the test data is 1,0,0,which causes me TLE problem.And I have tested this data with my own program,and there is no problem.


  • 0
    L

    I also encountered the same problem with the test [1,0,0], but not know why


Log in to reply
 

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